fastapi.missing_cors
Correctness
Medium
Detects FastAPI app without CORSMiddleware added.
Why It Matters
Section titled “Why It Matters”Without CORS configuration:
- Browser requests fail — Browsers block cross-origin requests by default
- Frontend can’t call API — Your React/Vue/Angular app gets CORS errors
- Mobile web broken — WebViews have the same restrictions
- Development pain — Works with curl but fails in browsers
If your API serves web clients from different origins, CORS is mandatory.
Example
Section titled “Example”# ❌ Beforefrom fastapi import FastAPI
app = FastAPI()
@app.get("/api/users")def get_users(): return usersBrowser requests from https://myapp.com to https://api.myapp.com fail with CORS error.
# ✅ Afterfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["https://myapp.com"], allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["*"],)
@app.get("/api/users")def get_users(): return usersWhat Unfault Detects
Section titled “What Unfault Detects”- FastAPI app without
CORSMiddleware - CORS middleware with
allow_origins=["*"]andallow_credentials=True(security issue)
Auto-Fix
Section titled “Auto-Fix”Unfault adds CORSMiddleware with sensible defaults. Review and restrict origins for production.
Security Considerations
Section titled “Security Considerations”# DANGEROUS: Don't do thisapp.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows any origin allow_credentials=True, # Sends cookies)
# SAFE: Be specificapp.add_middleware( CORSMiddleware, allow_origins=[ "https://myapp.com", "https://staging.myapp.com", ], allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE"], allow_headers=["Authorization", "Content-Type"],)