Fix Security Misconfiguration in FastAPI
FastAPI's 'batteries-included' approach is a double-edged sword. Out-of-the-box, it often leaks sensitive metadata, enables permissive CORS, and leaves documentation endpoints wide open for automated reconnaissance. A hardened FastAPI instance requires explicit environment-aware configuration to kill the noise and shut down common attack vectors like Cross-Origin Resource Sharing (CORS) abuse and Information Leakage via stack traces.
The Vulnerable Pattern
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddlewareVULN: Debug mode enabled leaks stack traces
app = FastAPI(debug=True)
VULN: Wildcard CORS allows any origin to read response data
app.add_middleware( CORSMiddleware, allow_origins=[""], allow_credentials=True, allow_methods=[""], allow_headers=[”*”], )
@app.get(“/config”) def get_internal_config(): return {“db_string”: “postgres://admin:password@localhost:5432/db”}
The Secure Implementation
The secure implementation addresses four critical areas. 1. Environment Isolation: By checking APP_ENV, we disable the /docs and /openapi.json endpoints in production, preventing attackers from mapping the entire API schema. 2. CORS Hardening: We replace the wildcard '*' with a whitelist of trusted domains, stopping unauthorized cross-domain data exfiltration. 3. Information Leakage: Setting debug=False ensures that internal server errors don't dump Python stack traces or environment variables to the client. 4. Defense-in-Depth: We manually inject essential security headers (HSTS, CSP, X-Frame-Options) via custom middleware to mitigate clickjacking and protocol downgrade attacks.
import os from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.middleware.base import BaseHTTPMiddlewareLoad environment: default to production for safety
ENV = os.getenv(“APP_ENV”, “production”) ALLOWED_ORIGINS = os.getenv(“ALLOWED_ORIGINS”, “https://app.example.com”).split(”,“)
Hardening: Disable docs and debug in production
app = FastAPI( debug=False, docs_url=None if ENV == “production” else “/docs”, redoc_url=None if ENV == “production” else “/redoc”, openapi_url=None if ENV == “production” else “/openapi.json” )
Strict CORS Policy
app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_credentials=True, allow_methods=[“GET”, “POST”], allow_headers=[“Authorization”, “Content-Type”], )
Injecting Security Headers
@app.middleware(“http”) async def add_security_headers(request, call_next): response = await call_next(request) response.headers[“X-Content-Type-Options”] = “nosniff” response.headers[“X-Frame-Options”] = “DENY” response.headers[“Strict-Transport-Security”] = “max-age=31536000; includeSubDomains” response.headers[“Content-Security-Policy”] = “default-src ‘self’” return response
Your FastAPI API
might be exposed to Security Misconfiguration
74% of FastAPI apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.