安全修复: - 创建 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:
@@ -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中间件"""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user