mcpField
S
security-fastapi

security-fastapi

github.com/igorwarzocha安全122141 次安装38 周前更新
代码仓库

关于 security-fastapi

security-fastapi 是面向 FastAPI 应用的安全审计技能,涵盖身份验证依赖、CORS 和中间件检查。适用于检查 API 路由访问控制与生产环境安全设置的开发者。

主要功能

  1. 01检查路由的身份验证依赖
  2. 02审查 API 密钥方案与 CORS 配置
  3. 03检查主机头防护和 HTTPS 强制跳转
  4. 04通过命令扫描路由与身份验证用法

适用场景

  1. 01审计 FastAPI 路由的访问控制
  2. 02检查带凭据请求的 CORS 来源配置
  3. 03核查生产环境的主机与 HTTPS 防护

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/igorwarzocha/opencode-workflows --skill security-fastapi

安装后在 Claude Code 中输入/security-fastapi确认已加载。

附带文件scripts/scan.sh

详细介绍

针对 FastAPI 应用的安全审计模式,涵盖身份验证依赖项、CORS 配置和中间件安全。

需要检查的核心风险

路由缺少身份验证

FastAPI 需要通过路由或路由器上的依赖项实现身份验证/授权。如果未使用 Depends()/Security(),请检查每个路由,确认是否存在非预期的公开访问。

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 密钥方案

如果使用 API 密钥,SHOULD 优先选择基于请求头的方案(APIKeyHeader),并在服务端验证密钥。

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:避免与凭据一起使用通配符

使用 allow_origins=["*"] 时,带凭据的请求(Cookie/Authorization)将被排除。对于已通过身份验证的浏览器客户端,MUST 明确列出允许的来源。

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Host 请求头与 HTTPS 强制要求

SHOULD 使用 Starlette 中间件防止 Host 请求头攻击,并在生产环境中强制使用 HTTPS。

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)

快速审计命令

# Detect FastAPI usage
rg -n "fastapi" pyproject.toml requirements*.txt

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

# Check for auth dependencies
rg -n "Depends\(|Security\(" . -g "*.py"

# CORS config and wildcards
rg -n "CORSMiddleware|allow_origins|allow_credentials" . -g "*.py"

# TrustedHost/HTTPS middleware
rg -n "TrustedHostMiddleware|HTTPSRedirectMiddleware" . -g "*.py"

安全加固清单

  • 所有敏感路由都需要 Depends() 或 Security() 身份验证依赖项
  • API 密钥方案使用请求头(APIKeyHeader),而非查询参数
  • 当 allow_credentials=True 时,allow_origins 设置为明确的值
  • 为生产环境域名配置 TrustedHostMiddleware
  • 在生产环境启用 HTTPSRedirectMiddleware(或由代理强制执行)

脚本

  • scripts/scan.sh - 对 FastAPI 进行初步安全扫描

评论

支持 Markdown