security-fastapi

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<overview>
Security audit patterns for FastAPI applications covering authentication dependencies, CORS configuration, and middleware security.
</overview> <vulnerabilities>
<overview>
FastAPI应用的安全审计模式,涵盖认证依赖项、CORS配置和中间件安全。
</overview> <vulnerabilities>

Core Risks to Check

需检查的核心风险

Missing Auth on Routes

路由缺失认证

FastAPI expects authentication/authorization via dependencies on routes or routers. If no
Depends()
/
Security()
usage exists, review every route for unintended public access.
python
from fastapi import Depends, Security

@app.get("/private")
async def private_route(user=Depends(get_current_user)):
    return {"ok": True}

@app.get("/scoped")
async def scoped_route(user=Security(get_current_user, scopes=["items"])):
    return {"ok": True}
FastAPI期望通过路由或路由器上的依赖项实现认证/授权。如果未使用
Depends()
/
Security()
,需检查每个路由是否存在意外的公共访问情况。
python
from fastapi import Depends, Security

@app.get("/private")
async def private_route(user=Depends(get_current_user)):
    return {"ok": True}

@app.get("/scoped")
async def scoped_route(user=Security(get_current_user, scopes=["items"])):
    return {"ok": True}

API Key Schemes

API密钥方案

If using API keys, SHOULD prefer header-based schemes (
APIKeyHeader
) and validate the key server-side.
python
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader

api_key = APIKeyHeader(name="x-api-key")

@app.get("/items")
async def read_items(key: str = Depends(api_key)):
    return {"key": key}
如果使用API密钥,应优先采用基于头部的方案(
APIKeyHeader
)并在服务器端验证密钥。
python
from fastapi import Depends, FastAPI
from fastapi.security import APIKeyHeader

api_key = APIKeyHeader(name="x-api-key")

@app.get("/items")
async def read_items(key: str = Depends(api_key)):
    return {"key": key}

CORS: Avoid Wildcards with Credentials

CORS:避免在启用凭证时使用通配符

Using
allow_origins=["*"]
excludes credentialed requests (cookies/Authorization). For authenticated browser clients, MUST explicitly list allowed origins.
python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
使用
allow_origins=["*"]
会排除带凭证的请求(Cookie/Authorization)。对于已认证的浏览器客户端,必须显式列出允许的源地址。
python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Host Header and HTTPS Enforcement

主机头与HTTPS强制

SHOULD use Starlette middleware to prevent host-header attacks and enforce HTTPS in production.
python
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware

app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])
app.add_middleware(HTTPSRedirectMiddleware)
</vulnerabilities> <commands>
应使用Starlette中间件防止主机头攻击,并在生产环境中强制使用HTTPS。
python
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware

app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"])
app.add_middleware(HTTPSRedirectMiddleware)
</vulnerabilities> <commands>

Quick Audit Commands

快速审计命令

bash
undefined
bash
undefined

Detect FastAPI usage

Detect FastAPI usage

rg -n "fastapi" pyproject.toml requirements*.txt
rg -n "fastapi" pyproject.toml requirements*.txt

Find routes

Find routes

rg -n "@app.(get|post|put|patch|delete)" . -g "*.py"
rg -n "@app.(get|post|put|patch|delete)" . -g "*.py"

Check for auth dependencies

Check for auth dependencies

rg -n "Depends(|Security(" . -g "*.py"
rg -n "Depends(|Security(" . -g "*.py"

CORS config and wildcards

CORS config and wildcards

rg -n "CORSMiddleware|allow_origins|allow_credentials" . -g "*.py"
rg -n "CORSMiddleware|allow_origins|allow_credentials" . -g "*.py"

TrustedHost/HTTPS middleware

TrustedHost/HTTPS middleware

rg -n "TrustedHostMiddleware|HTTPSRedirectMiddleware" . -g "*.py"

</commands>

<checklist>
rg -n "TrustedHostMiddleware|HTTPSRedirectMiddleware" . -g "*.py"

</commands>

<checklist>

Hardening Checklist

加固清单

  • All sensitive routes require
    Depends()
    or
    Security()
    auth dependencies
  • API key schemes use headers (
    APIKeyHeader
    ), not query params
  • allow_origins
    is explicit when
    allow_credentials=True
  • TrustedHostMiddleware
    configured for production domains
  • HTTPSRedirectMiddleware
    enabled in production (or enforced by proxy)
</checklist> <scripts>
  • 所有敏感路由都要求使用
    Depends()
    Security()
    认证依赖项
  • API密钥方案使用头部(
    APIKeyHeader
    )而非查询参数
  • allow_credentials=True
    时,
    allow_origins
    设置为显式值
  • 为生产环境域名配置
    TrustedHostMiddleware
  • 生产环境中启用
    HTTPSRedirectMiddleware
    (或由代理强制实施)
</checklist> <scripts>

Scripts

脚本

  • scripts/scan.sh
    - First-pass FastAPI security scan
</scripts>
  • scripts/scan.sh
    - FastAPI安全初步扫描脚本
</scripts>