Security & Compatibility Middleware
Relevant source files
The following files were used as context for generating this wiki page:
Security and Compatibility middleware in Starlette provide essential layers for protecting applications from common web vulnerabilities and ensuring interoperability between different Python web standards. These components handle tasks ranging from Cross-Origin Resource Sharing (CORS) and host validation to integrating legacy WSGI applications into modern ASGI stacks.
Starlette applications automatically structure these middlewares into a stack. ServerErrorMiddleware is positioned as the outermost layer to capture any unhandled exceptions, while ExceptionMiddleware serves as the innermost layer to handle routed exceptions. Sources: starlette/applications.py:46-51, starlette/applications.py:72-76
Cross-Origin Resource Sharing (CORS)
The CORSMiddleware implements the standard logic for handling Cross-Origin Resource Sharing. It manages both "simple" requests and "preflight" requests by inspecting the Origin header and validating it against allowed configurations.
Request Logic and Flow
The middleware differentiates between standard HTTP methods and OPTIONS preflight requests that contain CORS-specific headers.
The diagram shows the decision tree for CORS processing. Sources: starlette/middleware/cors.py:80-97
Preflight and Simple Responses
- Preflight Responses: Validates
Origin,Access-Control-Request-Method, andAccess-Control-Request-Headers. If any validation fails, it returns a 400 Bad Request with a descriptive failure message. Sources: starlette/middleware/cors.py:108-144 - Simple Responses: Wraps the ASGI
sendcallable to inject appropriate CORS headers into the response if the request is allowed. Sources: starlette/middleware/cors.py:146-168
| Parameter | Type | Default | Description |
|---|---|---|---|
allow_origins | Sequence[str] | () | List of origins allowed to make cross-site requests. |
allow_methods | Sequence[str] | ("GET",) | List of allowed HTTP methods. * allows all standard methods. |
allow_headers | Sequence[str] | () | List of allowed HTTP headers. |
allow_credentials | bool | False | Whether to allow cookies in cross-site requests. |
max_age | int | 600 | Seconds the preflight result can be cached. |
Sources: starlette/middleware/cors.py:18-35
Server Error & Debugging
ServerErrorMiddleware provides a safety net for unhandled exceptions. It can return a default "Internal Server Error" message or a detailed HTML/Plain Text traceback when in debug mode. Sources: starlette/middleware/errors.py:133-143
Debug Traceback Generation
When debug=True, the middleware inspects the exception stack to build an interactive HTML traceback page. It uses a traceback.TracebackException to capture local variables and frame information. Sources: starlette/middleware/errors.py:207-227
The sequence shows how exceptions are caught and processed based on the debug state. Sources: starlette/middleware/errors.py:155-180
WSGI Compatibility
The WSGIMiddleware allows Starlette to host legacy WSGI applications. It translates ASGI scopes and bodies into the WSGI environ dictionary and bridges the synchronous WSGI execution with the asynchronous ASGI environment. Sources: starlette/middleware/wsgi.py:75-80
Environment Translation
The build_environ function maps ASGI scope keys to WSGI standard environment variables.
scope["method"]maps toREQUEST_METHOD.scope["root_path"]maps toSCRIPT_NAME.scope["path"]maps toPATH_INFO.- Headers are transformed to
HTTP_prefixed uppercase keys.
Sources: starlette/middleware/wsgi.py:23-63
Concurrency Architecture
WSGI applications are synchronous. To prevent blocking the async event loop, WSGIMiddleware uses anyio.to_thread.run_sync to execute the WSGI application in a separate thread. Sources: starlette/middleware/wsgi.py:100-104
Visualization of the ASGI-to-WSGI bridging process. Sources: starlette/middleware/wsgi.py:92-132
Authentication Middleware
While the core implementation is found in starlette/middleware/authentication.py, its behavior is defined by the AuthenticationBackend. It provides a centralized mechanism for populating request.user and request.auth. Sources: tests/test_authentication.py:27-35
- Logic: Intercepts the request, calls the provided
backend.authenticate(request), and stores the resultingAuthCredentialsand user object in the request scope. - Error Handling: Supports an
on_errorcallable to return custom responses when authentication fails. Sources: tests/test_authentication.py:241-244
Trusted Host Validation
The TrustedHostMiddleware (referenced in Starlette application setups) ensures that the Host header of incoming requests matches a whitelist of allowed patterns. This prevents HTTP Host Header attacks.
- Patterns: Supports literal strings and wildcard subdomains (e.g.,
*.example.com). Sources: tests/test_applications.py:136-138 - Failure: If the host is invalid, it returns a 400 Bad Request. Sources: tests/test_applications.py:245-249
Summary
Starlette's middleware suite ensures that applications remain secure (via CORS and TrustedHost), compatible with older standards (via WSGI), and resilient to failures (via ServerError). These components are designed to be composable, allowing developers to add specific layers of security and compatibility as needed for their specific deployment environment.