Fix Improper Assets Management in FastAPI
Improper Assets Management (OWASP API9:2023) occurs when legacy, shadow, or unpatched API versions remain exposed, or when sensitive documentation (Swagger/Redoc) is accessible in production. In FastAPI, the default behavior is to serve auto-generated documentation and OpenAPI schemas, which provides an attacker with a complete map of your attack surface, including hidden parameters and internal logic.
The Vulnerable Pattern
from fastapi import FastAPIVULNERABLE: Default settings enable /docs and /redoc in production
app = FastAPI()
@app.get(“/api/v1/users”) def get_users(): return {“status”: “active”}
VULNERABLE: Legacy endpoint left active without authentication
@app.get(“/api/v1/debug_internal_state”) def legacy_debug(): return {“db_connection”: “established”, “version”: “0.0.1-alpha”}
The Secure Implementation
To mitigate Improper Assets Management: 1. Disable Swagger UI and ReDoc in production by setting `docs_url=None` and `redoc_url=None`. 2. Implement a strict API versioning strategy (e.g., /v2/) and actively decommission old versions. 3. Use environment variables to toggle features, ensuring debug routes never reach production. 4. Maintain an inventory of all deployed API hosts and versions to prevent 'Shadow APIs' from existing outside your security perimeter.
import os from fastapi import FastAPI from fastapi.openapi.utils import get_openapiLoad environment to check deployment stage
ENV = os.getenv(“APP_ENV”, “production”)
SECURE: Disable documentation endpoints in production
app = FastAPI( 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” )
@app.get(“/api/v2/users”) def get_users(): return {“status”: “active”}
SECURE: Legacy endpoints should be decommissioned or strictly gated
If migration is ongoing, use header-based versioning or strict IP whitelisting
Your FastAPI API
might be exposed to Improper Assets Management
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.