presidio-v/presidio-hardened-fastapi

GitHub: presidio-v/presidio-hardened-fastapi

一个 FastAPI 的安全强化替换包,通过替换 import 即可为 API 自动启用严格 CORS、速率限制、安全响应头、依赖审计和日志脱敏等开箱即用的安全默认配置。

Stars: 56 | Forks: 1

# presidio-hardened-fastapi 一个经过强化的、近乎可以直接替换 FastAPI 的方案,具有强大的默认安全设置。 ## 快速开始 ``` pip install presidio-hardened-fastapi ``` ``` # 只需替换 import —— 你现有的 FastAPI 代码即可获得安全默认值。 from presidio_fastapi import FastAPI, APIRouter app = FastAPI(title="My Secure API") @app.get("/") async def root(): return {"status": "hardened"} ``` ## v0.2.0 版本更新 - 通过 RedactingFilter 实现接收器级别的敏感信息脱敏(logger 会自动应用)。 - 将 pip-audit 集成到开发扩展依赖和 CI 中。 - 更新了文档以确保准确性(脱敏/验证是强大的辅助工具;请在输入时显式调用它们)。 - 改进了版本和依赖项。 ## 你将获得的功能(自动) | 安全特性 | 普通 FastAPI | presidio-hardened-fastapi | |---|---|---| | **CORS** | 默认完全开放 | 严格锁定 — 除非配置,否则不允许任何来源 | | **速率限制** | 无 | 每个 IP 60 req/min,带有指数退避(可配置) | | **安全 Header** | 无 | CSP, HSTS, X-Frame-Options, X-Content-Type-Options 等 | | **敏感信息脱敏** | 无 | 辅助工具 + 在 presidio_fastapi 日志上自动应用接收器级别的 RedactingFilter (v0.2) | | **OWASP 验证** | 仅支持 Pydantic | SQL injection, XSS, 路径遍历检查(可选辅助工具:调用 check_owasp()) | | **依赖项检查** | 无 | 启动时检查 + 在 [dev]/CI 中使用 pip-audit (v0.2) | | **安全日志记录** | 无 | 结构化的安全事件日志(带有接收器级别脱敏) | ## 并排对比 ### 普通 FastAPI ``` from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 你必须手动添加 CORS... app.add_middleware( CORSMiddleware, allow_origins=["*"], # dangerous! allow_methods=["*"], allow_headers=["*"], ) # 没有速率限制 # 没有安全标头 # 除了 Pydantic 外没有输入验证 # 没有密钥脱敏 @app.post("/login") async def login(data: dict): return {"token": "sk-live-abc123secret"} # leaked! ``` ### presidio-hardened-fastapi ``` from presidio_fastapi import FastAPI, Request, check_owasp, redact_dict app = FastAPI( title="My Secure API", cors_allow_origins=["https://myapp.com"], # explicit allowlist ) @app.post("/login") async def login(request: Request): body = await request.json() check_owasp(body) # blocks SQL injection, XSS, path traversal # Process login... response_data = {"token": "sk-live-abc123secret"} return redact_dict(response_data) # token is redacted in response ``` **零额外代码即可应用的自动保护 (v0.2):** - 严格的 CORS(仅限 `https://myapp.com`) - 速率限制(每个 IP 60 req/min) - 安全 Header (CSP, HSTS, X-Frame-Options, ...) - 所有 presidio_fastapi 日志上的接收器级别脱敏 - 启动时依赖审计(外加可用的 pip-audit) - 安全事件记录 注意:`check_owasp()` 和 `redact_*` 是强大的辅助工具 —— 请在不受信任的输入/响应数据上调用它们以获得完整效果(为了避免破坏现有的 Pydantic 模型,主体部分的验证/脱敏并非完全自动化)。 ## 配置 ``` from presidio_fastapi import FastAPI app = FastAPI( cors_allow_origins=["https://trusted.com"], cors_allow_methods=["GET", "POST"], cors_allow_headers=["Authorization"], cors_allow_credentials=True, enable_rate_limiting=True, enable_owasp_validation=True, enable_dep_check=True, security_headers={ "Content-Security-Policy": "default-src 'self' https://cdn.example.com", }, ) ``` ## 路由级别的速率限制 ``` from presidio_fastapi import FastAPI, Request from presidio_fastapi import limiter app = FastAPI() @app.get("/expensive") @limiter.limit("5/minute") async def expensive_endpoint(request: Request): return {"data": "rate-limited to 5/min"} ``` ## 脱敏工具 ``` from presidio_fastapi import redact_dict, redact_value data = {"user": "alice", "api_key": "sk-live-xxxxxxxxxxxx"} safe = redact_dict(data) # {"user": "alice", "api_key": "***REDACTED***"} ``` ## OWASP 输入验证 ``` from presidio_fastapi import check_owasp, HTTPException try: check_owasp({"query": "'; DROP TABLE users;--"}) except HTTPException as e: print(e.detail) # "Potential SQL injection detected" ``` ## 开发 ``` git clone https://github.com/presidio-v/presidio-hardened-fastapi cd presidio-hardened-fastapi uv venv .venv && source .venv/bin/activate uv pip install -e ".[dev]" # 运行测试 pytest --cov=presidio_fastapi # Lint 和格式化 ruff format . ruff check . --fix ``` ## 安全 有关安全策略和漏洞报告说明,请参阅 [SECURITY.md](SECURITY.md)。 ## 许可证 MIT — 详情请参阅 [LICENSE](LICENSE)。 ## SDLC 此仓库是在 Presidio hardened-family SDLC 下开发的: .
标签:API安全, AV绕过, FastAPI, GitHub Advanced Security, JSON输出, Python, Web开发框架, 安全加固, 安全规则引擎, 安全防护, 无后门, 逆向工具