Consider this FastAPI app with TrustedHostMiddleware configured to allow only 'example.com' and 'localhost'. What will be the HTTP status code when a request comes from 'example.com'?
from fastapi import FastAPI from starlette.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'localhost']) @app.get('/') async def root(): return {'message': 'Hello World'}
TrustedHostMiddleware blocks requests from hosts not in the allowed list.
Requests from allowed hosts pass through and get normal responses, so status code 200 is returned.
Given the same FastAPI app with TrustedHostMiddleware allowing only 'example.com' and 'localhost', what is the response status code when a request comes from 'malicious.com'?
from fastapi import FastAPI from starlette.middleware.trustedhost import TrustedHostMiddleware app = FastAPI() app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'localhost']) @app.get('/') async def root(): return {'message': 'Hello World'}
TrustedHostMiddleware returns a 400 Bad Request for disallowed hosts.
Requests from hosts not in the allowed list get a 400 Bad Request response.
How do you configure TrustedHostMiddleware to allow 'example.com' and any subdomain like 'api.example.com'?
Wildcard subdomains must start with '*.' exactly.
Allowed hosts must include 'example.com' and '*.example.com' to cover the domain and all subdomains.
Given this code, why do all requests return 400 even from 'localhost'?
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['localhost:8000'])Check if ports are allowed in hostnames for TrustedHostMiddleware.
TrustedHostMiddleware matches only hostnames without ports. Including port causes mismatch and 400.
Why should you use TrustedHostMiddleware in your FastAPI app?
Think about what the Host header in HTTP requests can be used for in attacks.
TrustedHostMiddleware blocks requests with unexpected Host headers, preventing host header attacks.