Overly permissive FastAPI CORS settings

Overly permissive FastAPI CORS settings

Description

In FastAPI or Starlette, allowing every origin with allow_credentials=True can expose credentialed cross-origin responses to untrusted sites or conflict with browser and framework requirements. The official documentation requires explicit values for allow_origins, allow_methods and allow_headers when credentials are allowed, rather than ["*"].

Potential impact

  • Untrusted sites may make requests with session cookies or other authentication information when the browser permits those credentials.
  • Sensitive API responses may be exposed to unintended frontends or malicious sites.
  • A mismatch between the policy and response headers may also break legitimate browser requests. CORS settings do not replace server-side authentication or authorization.

Remediation

  • When using allow_credentials=True, restrict allow_origins, allow_methods and allow_headers to explicit allow-lists.
  • Avoid origin patterns that match everything, including allow_origin_regex=".*", allow_origin_regex="^.*$", allow_origin_regex=".+" and allow_origin_regex="^.+$".
  • Maintain separate allow-lists for each environment and permit only necessary origins in production. Retain server-side authentication, authorization and any required CSRF protection.

Examples

Before

python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

After

python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type"],
)

Explanation:

  • Before: Enables credentials while using wildcards for origins, methods and headers. Actual access to cross-origin responses depends on the response headers and the browser's credential handling.
  • After: Even when credentials are needed, explicitly allows only trusted origins and necessary methods and headers.

References