fix(Security): Host header injection auth bypass and forged admin embedded token (CNVD)

- TokenMiddleware/ResponseMiddleware/audit logger use scope['path']
  instead of request.url.path for whitelist checks: a crafted Host
  header (e.g. x/api/v1/mcp) was concatenated into Starlette's URL
  and made protected routes match the /mcp* whitelist entry
- validateEmbedded rejects admin accounts and non-type-4 apps, so a
  self-signed token with account=admin can no longer impersonate the
  administrator
- Add HostValidationMiddleware rejecting malformed Host headers at the
  outermost layer (defense in depth)
- Add regression tests for host validation, whitelist matching and
  source-level guards

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
fit2cloud-chenyw
2026-08-31 11:05:05 +08:00
committed by fit2cloud-chenyw
co-authored by Claude
parent cc8a7546e9
commit bbfc4cc8f5
6 changed files with 311 additions and 6 deletions
@@ -440,7 +440,7 @@ class SystemLogger:
module=config.module,
resource_id=str(resource_id),
request_method=request.method if request else None,
request_path=request.url.path if request else None,
request_path=(request.scope.get("path") or request.url.path) if request else None,
request_params=request_params,
create_time=datetime.now(),
remark=remark
+21
View File
@@ -0,0 +1,21 @@
import re
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse
# 合法 Host:域名 / IPv4 / IPv6(含端口),排除 '/'、'@'、空白等非法字符。
# Starlette 的 URL(scope) 会把 Host 头原始值拼进 URL,Host 携带路径片段会污染
# request.url.path 等派生属性(历史上被用于绕过认证白名单),因此请求入口处直接拒绝。
_HOST_RE = re.compile(r'^[A-Za-z0-9.\-:\[\]]{1,255}$')
class HostValidationMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
host = request.headers.get("host")
if not host or not _HOST_RE.match(host):
return JSONResponse(
{"code": 400, "data": None, "msg": "invalid host header"},
status_code=400,
)
return await call_next(request)
+1 -1
View File
@@ -40,7 +40,7 @@ class ResponseMiddleware(BaseHTTPMiddleware):
path_pattern = '' if not route else route.path_format
if (isinstance(response, JSONResponse)
or request.url.path == f"{settings.CONTEXT_PATH}/openapi.json"
or (request.scope.get("path") or request.url.path) == f"{settings.CONTEXT_PATH}/openapi.json"
or path_pattern in direct_paths):
return response
if response.status_code != 200: