Injection

How to Fix Injection in FastAPI [Month Year] [CVE-2021-32677]

[Fixed month year] or [Updated month year] Updated CVE-2021-32677

Overview

In FastAPI versions older than 0.65.2, when cookies were used for authentication on endpoints that accepted JSON payloads, parsing could leak across content-type boundaries. Specifically, FastAPI would attempt to read and parse the request body as JSON even if the Content-Type header was not a JSON media type (for example text/plain). A cross-site request from a browser could then include a JSON payload while relying on the user's cookies for authentication, enabling CSRF-style actions if the endpoint performed state-changing operations. This behavior allowed a malicious site to inject data into the application by posting with a non-JSON content type while still triggering actions on behalf of an authenticated user. The issue was fixed in FastAPI 0.65.2 by ensuring the body is parsed as JSON only when the content-type is application/json or a compatible JSON media type (e.g., application/geo+json). This CVE is documented as CVE-2021-32677 (CWE-352). Upgrade to the fixed version or apply mitigations if upgrading isn’t possible, such as content-type checks via middleware and stricter input handling. This class of vulnerability manifests in FastAPI when endpoints rely on cookies for authentication and process JSON payloads without strictly validating the request Content-Type. Attackers can craft requests from a malicious site that include JSON data but use a non-JSON content type, bypassing certain CORS preflight expectations and abusing the browser's handling of cross-origin requests. By combining crafted payloads with authenticated sessions, an attacker could perform unauthorized state-changing operations, underscoring the importance of proper input validation, content-type enforcement, and robust CSRF protections. The recommended remedy is to upgrade to 0.65.2 or newer and/or implement explicit content-type validation and safer authentication patterns. In short, this vulnerability highlights how permissive JSON parsing based on content type can enable CSRF-like data injection when cookies are involved. Upgrading and hardening request handling stops attackers from bypassing expected content-type semantics.

Affected Versions

< 0.65.2

Code Fix Example

FastAPI API Security Remediation
Vulnerable pattern:

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/transfer")
async def transfer(request: Request):
    # Vulnerable: request.json() may parse payload regardless of Content-Type in older FastAPI
    payload = await request.json()
    amount = payload.get("amount")
    # ... perform action using cookie-based session auth ...
    return {"status": "ok", "amount": amount}


Fixed pattern:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.responses import JSONResponse

app = FastAPI()

class TransferPayload(BaseModel):
    amount: float
    recipient: str = None  # optional field for demonstration

# Optional: enforce JSON content-type via middleware (see note in remediation steps)
from fastapi.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

class EnforceJSONMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        content_type = request.headers.get("content-type", "")
        if content_type:
            if "application/json" not in content_type and "geo+json" not in content_type:
                return JSONResponse(status_code=415, content={"detail": "Content-Type must be application/json or a compatible JSON type"})
        return await call_next(request)

app.add_middleware(EnforceJSONMiddleware)

@app.post("/transfer")
async def transfer(payload: TransferPayload):
    # Payload is parsed via Pydantic; parsing only occurs for proper JSON Content-Type
    return {"status": "ok", "amount": payload.amount, "recipient": payload.recipient}

CVE References

Choose which optional cookies to allow. You can change this any time.