Debian Codegraph @

docs/usage/middleware/builtin-middleware.rst

raw
1 Built-in middleware
2 ===================
3
4 CORS
5 ----
6
7 `CORS (Cross-Origin Resource Sharing) <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_ is a common security
8 mechanism that is often implemented using middleware. To enable CORS in a litestar application simply pass an instance
9 of :class:`~litestar.config.cors.CORSConfig` to :class:`~litestar.app.Litestar`:
10
11 .. code-block:: python
12
13 from litestar import Litestar
14 from litestar.config.cors import CORSConfig
15
16 cors_config = CORSConfig(allow_origins=["https://www.example.com"])
17
18 app = Litestar(route_handlers=[...], cors_config=cors_config)
19
20
21 CSRF
22 ----
23
24 `CSRF (Cross-site request forgery) <https://owasp.org/www-community/attacks/csrf>`_ is a type of attack where unauthorized commands are submitted from a user that the web
25 application trusts. This attack often uses social engineering that tricks the victim into clicking a URL that contains a
26 maliciously crafted, unauthorized request for a particular Web application. The user’s browser then sends this
27 maliciously crafted request to the targeted Web application. If the user is in an active session with the Web application,
28 the application treats this new request as an authorized request submitted by the user. Thus, the attacker can force the
29 user to perform an action the user didn't intend, for example:
30
31
32 .. code-block:: text
33
34 POST /send-money HTTP/1.1
35 Host: target.web.app
36 Content-Type: application/x-www-form-urlencoded
37
38 amount=1000usd&[email protected]
39
40
41 This middleware prevents CSRF attacks by doing the following:
42
43 1. On the first "safe" request (e.g GET) - set a cookie with a special token created by the server
44 2. On each subsequent "unsafe" request (e.g POST) - make sure the request contains either a
45 form field or an additional header that has this token (more on this below)
46
47 To enable CSRF protection in a Litestar application simply pass an instance of
48 :class:`~litestar.config.csrf.CSRFConfig` to the Litestar constructor:
49
50 .. code-block:: python
51
52 from litestar import Litestar, get, post
53 from litestar.config.csrf import CSRFConfig
54
55
56 @get()
57 async def get_resource() -> str:
58 # GET is one of the safe methods
59 return "some_resource"
60
61 @post("{id:int}")
62 async def create_resource(id: int) -> bool:
63 # POST is one of the unsafe methods
64 return True
65
66 csrf_config = CSRFConfig(secret="my-secret")
67
68 app = Litestar([get_resource, create_resource], csrf_config=csrf_config)
69
70
71 The following snippet demonstrates how to change the cookie name to ``"some-cookie-name"`` and header name to ``"some-header-name"``.
72
73 .. code-block:: python
74
75 csrf_config = CSRFConfig(secret="my-secret", cookie_name='some-cookie-name', header_name='some-header-name')
76
77
78 A CSRF protected route can be accessed by any client that can make a request with either the header or form-data key.
79
80
81 .. note::
82
83 The form-data key can not be currently configured. It should only be passed via the key ``"_csrf_token"``
84
85 In Python, any client such as `requests <https://github.com/psf/requests>`_ or `httpx <https://github.com/encode/httpx>`_ can be used.
86 The usage of clients or sessions is recommended due to the cookie persistence it offers across requests.
87 The following is an example using `httpx.Client <https://www.python-httpx.org/api/#client>`_.
88
89 .. code-block:: python
90
91 import httpx
92
93
94 with httpx.Client() as client:
95 get_response = client.get("http://localhost:8000/")
96
97 # "csrftoken" is the default cookie name
98 csrf = get_response.cookies["csrftoken"]
99
100 # "x-csrftoken" is the default header name
101 post_response_using_header = client.post("http://localhost:8000/1", headers={"x-csrftoken": csrf})
102 assert post_response_using_header.status_code == 201
103
104 # "_csrf_token" is the default *non* configurable form-data key
105 post_response_using_form_data = client.post("http://localhost:8000/1", data={"_csrf_token": csrf})
106 assert post_response_using_form_data.status_code == 201
107
108 # despite the header being passed, this request will fail as it does not have a cookie in its session
109 # note the usage of ``httpx.post`` instead of ``client.post``
110 post_response_with_no_persisted_cookie = httpx.post("http://localhost:8000/1", headers={"x-csrftoken": csrf})
111 assert post_response_with_no_persisted_cookie.status_code == 403
112 assert "CSRF token verification failed" in post_response_with_no_persisted_cookie.text
113
114 Routes can be marked as being exempt from the protection offered by this middleware via
115 :ref:`handler opts <handler_opts>`
116
117 .. code-block:: python
118
119 @post("/post", exclude_from_csrf=True)
120 def handler() -> None: ...
121
122
123 If you need to exempt many routes at once you might want to consider using the
124 :attr:`~litestar.config.csrf.CSRFConfig.exclude` kwarg which accepts list of path
125 patterns to skip in the middleware.
126
127 .. seealso::
128
129 * `Safe and Unsafe (HTTP Methods) <https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP>`_
130 * `HTTPX Clients <https://www.python-httpx.org/advanced/clients>`_
131 * `Requests Session <https://requests.readthedocs.io/en/latest/user/advanced>`_
132
133
134 Allowed Hosts
135 -------------
136
137 Another common security mechanism is to require that each incoming request has a ``"Host"`` or ``"X-Forwarded-Host"`` header,
138 and then to restrict hosts to a specific set of domains - what's called "allowed hosts".
139
140 Litestar includes an :class:`~litestar.middleware.allowed_hosts.AllowedHostsMiddleware` class that can be
141 easily enabled by either passing an instance of :class:`~litestar.config.allowed_hosts.AllowedHostsConfig` or a
142 list of domains to :class:`~litestar.app.Litestar`:
143
144 .. code-block:: python
145
146 from litestar import Litestar
147 from litestar.config.allowed_hosts import AllowedHostsConfig
148
149 app = Litestar(
150 route_handlers=[...],
151 allowed_hosts=AllowedHostsConfig(
152 allowed_hosts=["*.example.com", "www.wikipedia.org"]
153 ),
154 )
155
156 .. note::
157
158 You can use wildcard prefixes (``*.``) in the beginning of a domain to match any combination of subdomains. Thus,
159 ``*.example.com`` will match ``www.example.com`` but also ``x.y.z.example.com`` etc. You can also simply put ``*``
160 in trusted hosts, which means allow all. This is akin to turning the middleware off, so in this case it may be
161 better to not enable it in the first place. You should note that a wildcard can only be used in the prefix of a
162 domain name, not in the middle or end. Doing so will result in a validation exception being raised.
163
164
165 Compression
166 -----------
167
168 HTML responses can optionally be compressed. Litestar has built in support for gzip and brotli. Gzip support is provided
169 through the built-in Starlette classes, and brotli support can be added by installing the ``brotli`` extras.
170
171 You can enable either backend by passing an instance of
172 :class:`~litestar.config.compression.CompressionConfig` to ``compression_config`` of
173 :class:`~litestar.app.Litestar`.
174
175 GZIP
176 ^^^^
177
178 You can enable gzip compression of responses by passing an instance of :class:`~litestar.config.compression.CompressionConfig` with
179 the ``backend`` parameter set to ``"gzip"``.
180
181 You can configure the following additional gzip-specific values:
182
183
184 * ``minimum_size``: the minimum threshold for response size to enable compression. Smaller responses will not be
185 compressed. Defaults is ``500``, i.e. half a kilobyte.
186 * ``gzip_compress_level``: a range between 0-9, see the `official python docs <https://docs.python.org/3/library/gzip.html>`_.
187 Defaults to ``9`` , which is the maximum value.
188
189 .. code-block:: python
190
191 from litestar import Litestar
192 from litestar.config.compression import CompressionConfig
193
194 app = Litestar(
195 route_handlers=[...],
196 compression_config=CompressionConfig(backend="gzip", gzip_compress_level=9),
197 )
198
199 Brotli
200 ^^^^^^
201
202 The `Brotli <https://pypi.org/project/Brotli>`_ package is required to run this middleware. It is available as an extras to litestar with the ``brotli``
203 extra (``pip install 'litestar[brotli]'``).
204
205 You can enable brotli compression of responses by passing an instance of
206 :class:`~litestar.config.compression.CompressionConfig` with the ``backend`` parameter set to ``"brotli"``.
207
208 You can configure the following additional brotli-specific values:
209
210
211 * ``minimum_size``: the minimum threshold for response size to enable compression. Smaller responses will not be
212 compressed. Default is 500, i.e. half a kilobyte
213 * ``brotli_quality``: Range [0-11], Controls the compression-speed vs compression-density tradeoff. The higher the
214 quality, the slower the compression. Defaults to 5
215 * ``brotli_mode``: The compression mode can be ``"generic"`` (for mixed content), ``"text"`` (for UTF-8 format text input), or
216 ``"font"`` (for WOFF 2.0). Defaults to ``"text"``
217 * ``brotli_lgwin``: Base 2 logarithm of size. Range [10-24]. Defaults to 22.
218 * ``brotli_lgblock``: Base 2 logarithm of the maximum input block size. Range [16-24]. If set to 0, the value will
219 be set based on the quality. Defaults to 0
220 * ``brotli_gzip_fallback``: a boolean to indicate if gzip should be used if brotli is not supported
221
222 .. code-block:: python
223
224 from litestar import Litestar
225 from litestar.config.compression import CompressionConfig
226
227 app = Litestar(
228 route_handlers=[...],
229 compression_config=CompressionConfig(backend="brotli", brotli_gzip_fallback=True),
230 )
231
232 Rate-Limit Middleware
233 ---------------------
234
235 Litestar includes an optional :class:`~litestar.middleware.rate_limit.RateLimitMiddleware` that follows
236 the `IETF RateLimit draft specification <https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/>`_.
237
238 To use the rate limit middleware, use the :class:`~litestar.middleware.rate_limit.RateLimitConfig`:
239
240 .. literalinclude:: /examples/middleware/rate_limit.py
241 :language: python
242
243 The only required configuration kwarg is ``rate_limit``, which expects a tuple containing a time-unit (``"second"``,
244 ``"minute"``, ``"hour"``, ``"day"``\ ) and a value for the request quota (integer).
245
246
247 Using behind a proxy
248 ^^^^^^^^^^^^^^^^^^^^
249
250 The default mode for uniquely identifiying client uses the client's address. When an
251 application is running behind a proxy, that address will be the proxy's, not the "real"
252 address of the end-user.
253
254 While there are special headers set by proxies to retrieve the remote client's actual
255 address (``X-FORWARDED-FOR``), their values should not implicitly be trusted, as any
256 client is free to set them to whatever value they want. A rate-limit could easily be
257 circumvented by spoofing these, and simply attaching a new, random address to each
258 request.
259
260 The best way to handle applications running behind a proxy is to use a middleware that
261 updates the client's address in a secure way, such as uvicorn's
262 `ProxyHeaderMiddleware <https://github.com/encode/uvicorn/blob/master/uvicorn/middleware/proxy_headers.py>`_
263 or hypercon's `ProxyFixMiddleware <https://hypercorn.readthedocs.io/en/latest/how_to_guides/proxy_fix.html>`_ .
264
265
266 Logging Middleware
267 ------------------
268
269 Litestar ships with a robust logging middleware that allows logging HTTP request and responses while building on
270 the Litestar's :ref:`logging configuration <logging-usage>`:
271
272 .. literalinclude:: /examples/middleware/logging_middleware.py
273 :language: python
274
275
276 The logging middleware uses the logger configuration defined on the application level, which allows for using any supported logging tool, depending on the configuration used
277 (see :ref:`logging configuration <logging-usage>` for more details).
278
279 Obfuscating Logging Output
280 ^^^^^^^^^^^^^^^^^^^^^^^^^^
281
282 Sometimes certain data, e.g. request or response headers, needs to be obfuscated. This is supported by the middleware
283 configuration:
284
285 .. code-block:: python
286
287 from litestar.middleware.logging import LoggingMiddlewareConfig
288
289 logging_middleware_config = LoggingMiddlewareConfig(
290 request_cookies_to_obfuscate={"my-custom-session-key"},
291 response_cookies_to_obfuscate={"my-custom-session-key"},
292 request_headers_to_obfuscate={"my-custom-header"},
293 response_headers_to_obfuscate={"my-custom-header"},
294 )
295
296 The middleware will obfuscate the headers ``Authorization`` and ``X-API-KEY`` , and the cookie ``session`` by default.
297
298
299 Compression and Logging of Response Body
300 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
301
302 If both :class:`~litestar.config.compression.CompressionConfig` and
303 :class:`~litestar.middleware.logging.LoggingMiddleware` have been defined for the application, the response
304 body will be omitted from response logging if it has been compressed, even if ``"body"`` has been included in
305 :class:`~litestar.middleware.logging.LoggingMiddlewareConfig.response_log_fields`. To force the body of
306 compressed responses to be logged, set
307 :attr:`~litestar.middleware.logging.LoggingMiddlewareConfig.include_compressed_body` to ``True`` , in
308 addition to including ``"body"`` in ``response_log_fields``.
309
310 Session Middleware
311 ------------------
312
313 Litestar includes a :class:`~litestar.middleware.session.base.SessionMiddleware`,
314 offering client- and server-side sessions. Server-side sessions are backed by Litestar's
315 :doc:`stores </usage/stores>`, which offer support for:
316
317 - In memory sessions
318 - File based sessions
319 - Redis based sessions
320 - Valkey based sessions
321 - Database based :ref:`advanced-alchemy:usage/frameworks/litestar:server-side session backend`
322
323 Setting up the middleware
324 ^^^^^^^^^^^^^^^^^^^^^^^^^
325
326 To start using sessions in your application all you have to do is create an instance
327 of a :class:`configuration <litestar.middleware.session.base.BaseBackendConfig>` object and
328 add its middleware to your application's middleware stack:
329
330 .. literalinclude:: /examples/middleware/session/cookies_full_example.py
331 :caption: Hello World
332 :language: python
333
334
335 .. note::
336
337 Since both client- and server-side sessions rely on cookies (one for storing the actual session
338 data, the other for storing the session ID), they share most of the cookie configuration.
339 A complete reference of the cookie configuration can be found at :class:`~litestar.middleware.session.base.BaseBackendConfig`.
340
341 Client-side sessions
342 ^^^^^^^^^^^^^^^^^^^^
343
344 Client side sessions are available through the :class:`~litestar.middleware.session.client_side.ClientSideSessionBackend`,
345 which offers strong AES-CGM encryption security best practices while support cookie splitting.
346
347 .. important::
348
349 ``ClientSideSessionBackend`` requires the `cryptography <https://cryptography.io/en/latest/>`_ library,
350 which can be installed together with litestar as an extra using ``pip install 'litestar[cryptography]'``
351
352 .. literalinclude:: /examples/middleware/session/cookie_backend.py
353 :caption: ``cookie_backend.py``
354 :language: python
355
356
357 .. seealso::
358
359 * :class:`~litestar.middleware.session.client_side.CookieBackendConfig`
360
361
362 Server-side sessions
363 ^^^^^^^^^^^^^^^^^^^^
364
365 Server side session store data - as the name suggests - on the server instead of the client.
366 They use a cookie containing a session ID which is a randomly generated string to identify a client
367 and load the appropriate data from the store
368
369 .. literalinclude:: /examples/middleware/session/file_store.py
370
371
372 .. seealso::
373
374 * :doc:`/usage/stores`
375 * :class:`~litestar.middleware.session.server_side.ServerSideSessionConfig`