fix: 修复权限提升漏洞和添加安全头
All checks were successful
continuous-integration/drone/push Build is passing

安全修复:
- 创建 UserSelfUpdate schema,禁止用户修改自己的 role 和 is_active
- /users/me 端点现在使用 UserSelfUpdate 而非 UserUpdate

安全增强:
- 添加 SecurityHeadersMiddleware 中间件
- X-Content-Type-Options: nosniff
- X-Frame-Options: DENY
- X-XSS-Protection: 1; mode=block
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: 禁用敏感功能
- Cache-Control: API响应不缓存
This commit is contained in:
yuliang_guo
2026-01-31 10:57:41 +08:00
parent 52dccaab79
commit 79b55cfd12
4 changed files with 54 additions and 4 deletions

View File

@@ -93,6 +93,39 @@ class RateLimitMiddleware(BaseHTTPMiddleware):
return response
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""
安全响应头中间件
添加各种安全相关的 HTTP 响应头
"""
async def dispatch(self, request: Request, call_next: Callable) -> Response:
response = await call_next(request)
# 防止 MIME 类型嗅探
response.headers["X-Content-Type-Options"] = "nosniff"
# 防止点击劫持
response.headers["X-Frame-Options"] = "DENY"
# XSS 过滤器(现代浏览器已弃用,但仍有一些旧浏览器支持)
response.headers["X-XSS-Protection"] = "1; mode=block"
# 引用策略
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
# 权限策略(禁用一些敏感功能)
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
# 缓存控制API 响应不应被缓存)
if request.url.path.startswith("/api/"):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
response.headers["Pragma"] = "no-cache"
return response
class RequestIDMiddleware(BaseHTTPMiddleware):
"""请求ID中间件"""