← Back to FastAPI, page 5

fastapi-0095 · Hard senior

How do you harden a FastAPI deployment: TrustedHost, HTTPS redirects, security headers, CORS, body size limits and docs exposure?

Layer defences. Restrict accepted Host headers with TrustedHostMiddleware, terminate HTTPS at a proxy and redirect HTTP (HTTPSRedirectMiddleware or at the proxy), add headers such as Strict-Transport-Security, X-Content-Type-Options and a Content-Security-Policy, configure CORS with explicit origins (never "*" with credentials), enforce request size limits in the proxy and in ASGI middleware, hide docs and OpenAPI in private services, and keep secrets and debug mode out of production.

Full answer

Checklist with reasons:

  • Host validation: TrustedHostMiddleware(allowed_hosts=["api.schoolabe.example"]) blocks Host-header attacks (poisoned password-reset links, cache poisoning). Requests with other hosts get 400.
  • HTTPS: terminate TLS at the load balancer or reverse proxy. Behind a proxy, run Uvicorn with --proxy-headers --forwarded-allow-ips=<proxy ip> so the app sees the real scheme and client IP; trust only your proxy, otherwise clients can spoof X-Forwarded-*. HTTPSRedirectMiddleware answers 307 for http requests, but redirecting at the proxy is usual.
  • Security headers (add through middleware or proxy): Strict-Transport-Security: max-age=31536000; includeSubDomains, X-Content-Type-Options: nosniff, Referrer-Policy, Cache-Control: no-store on sensitive responses, and CSP when serving HTML (APIs mostly return JSON, so focus on HSTS and nosniff).
  • CORS: CORSMiddleware with an explicit allow_origins list. allow_origins=["*"] cannot be combined with credentials; list methods and headers you need. CORS is a browser-side protection, not authentication.
  • Request limits: a body size cap (413) in proxy config and a pure ASGI middleware that counts bytes even for chunked uploads; limits on JSON depth and list lengths in models (max_length), and timeouts.
  • Rate limiting at the gateway (and per-user in the app for login and expensive routes), plus lockouts and monitoring on authentication endpoints.
  • Docs: disable /docs, /redoc and /openapi.json (docs_url=None, ...) for internal or sensitive APIs, or protect them.
  • Errors: do not leak stack traces; return generic 500 bodies, log details with a correlation ID. Keep debug=False.
  • Secrets: environment or secret manager, never in the repo; rotate; least-privilege database users.
  • Dependencies: pin and scan (pip-audit), update FastAPI/Starlette regularly (multipart parsing and path handling have had advisories), run containers as non-root with read-only file systems where possible.
  • Authentication and authorization are separate layers: see JWT validation and object-level authorization.
python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.testclient import TestClient

MAX_BODY = 1024


class SecurityHeaders:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)

        async def send_with_headers(message):
            if message["type"] == "http.response.start":
                headers = message.setdefault("headers", [])
                headers += [(b"x-content-type-options", b"nosniff"),
                            (b"strict-transport-security", b"max-age=31536000; includeSubDomains")]
            await send(message)

        await self.app(scope, receive, send_with_headers)


class BodyLimit:
    def __init__(self, app, limit):
        self.app, self.limit = app, limit

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        seen = 0
        too_big = False

        async def counted_receive():
            nonlocal seen, too_big
            message = await receive()
            if message["type"] == "http.request":
                seen += len(message.get("body", b""))
                if seen > self.limit:
                    too_big = True
                    return {"type": "http.request", "body": b"", "more_body": False}
            return message

        async def guarded_send(message):
            if too_big and message["type"] == "http.response.start":
                message = {"type": "http.response.start", "status": 413, "headers": [(b"content-type", b"text/plain")]}
            elif too_big and message["type"] == "http.response.body":
                message = {"type": "http.response.body", "body": b"Payload too large"}
            await send(message)

        await self.app(scope, counted_receive, guarded_send)


app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(BodyLimit, limit=MAX_BODY)
app.add_middleware(SecurityHeaders)
app.add_middleware(CORSMiddleware, allow_origins=["https://app.schoolabe.example"], allow_methods=["GET", "POST"], allow_headers=["Authorization"])
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.schoolabe.example"])
app.add_middleware(HTTPSRedirectMiddleware)


@app.post("/echo")
async def echo(payload: dict):
    return {"keys": sorted(payload)}


c = TestClient(app, base_url="https://api.schoolabe.example")
r = c.post("/echo", json={"a": 1})
print(r.status_code, r.json(), r.headers["x-content-type-options"], r.headers["strict-transport-security"])
print("big body:", c.post("/echo", content=b"x" * 5000, headers={"content-type": "application/json"}).status_code)
print("wrong host:", c.post("/echo", json={}, headers={"host": "evil.example"}).status_code)
print("docs hidden:", c.get("/docs").status_code, c.get("/openapi.json").status_code)
http = TestClient(app, base_url="http://api.schoolabe.example", follow_redirects=False)
resp = http.post("/echo", json={})
print("http ->", resp.status_code, resp.headers["location"])
pre = c.options("/echo", headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"})
print("CORS evil origin:", pre.status_code, pre.headers.get("access-control-allow-origin"))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {'keys': ['a']} nosniff max-age=31536000; includeSubDomains big body: 413 wrong host: 400 docs hidden: 404 404 http -> 307 https://api.schoolabe.example/echo CORS evil origin: 400 None

Key points

  • TrustedHost blocks forged Host headers
  • Trust forwarded headers only from your proxy
  • Explicit CORS origins; CORS is not authentication
  • Enforce body size limits at proxy and in ASGI middleware
  • Hide docs on private APIs; do not leak error details

Common mistakes

  • Using allow_origins=['*'] together with credentials
  • Trusting X-Forwarded headers from any client
  • No request size limit, which allows memory exhaustion
  • Leaving docs and debug output public on private APIs
  • Treating CORS as an authorization mechanism

Follow-ups

  • How do you configure Uvicorn behind nginx or a cloud load balancer?
  • What does a CSP buy an API?
  • How do you rate-limit login endpoints?

Tips

  • Go layer by layer
  • Name Host validation and forwarded headers
  • Mention limits and docs