Overview
In practice, security misconfigurations in FastAPI can lead to CSRF, information disclosure, or injection-like attacks when defaults are lax. Attackers may leverage cookie-based authentication and permissive request handling to exfiltrate or modify data without proper validation.
CVE-2021-32677 details: FastAPI < 0.65.2 could read a request payload as JSON even when the Content-Type was not application/json (for example text/plain). Because such requests can bypass CORS preflights, cookies could be sent and a CSRF could occur. This is fixed in 0.65.2.
CVE-2024-40627 details: The OpaMiddleware allowed all HTTP OPTIONS requests to pass unauthenticated, enabling an attacker to enumerate existing resources if an application differentiates responses by entity existence. The fix is in 2.0.1.
CVE-2024-42816 details: fastapi-admin pro v0.1.4 contained a cross-site scripting vulnerability via the Product Name parameter. An attacker could inject script that executes in an admin UI or downstream templates. Patch by upgrading and validating input.
Affected Versions
FastAPI < 0.65.2; fastapi-opa < 2.0.1; fastapi-admin pro v0.1.4
Code Fix Example
FastAPI API Security Remediation
Vulnerable pattern:
```python
from fastapi import FastAPI, Request
app = FastAPI()
@app.post('/items')
async def create_item(request: Request):
# Vulnerable: reads JSON payload regardless of Content-Type
data = await request.json()
return {'received': data}
```
Fixed pattern:
```python
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
@app.post('/items')
async def create_item(request: Request):
content_type = request.headers.get('content-type','')
if 'application/json' not in content_type and 'application/geo+json' not in content_type:
raise HTTPException(status_code=415, detail='Unsupported Media Type')
data = await request.json()
return {'received': data}
```