fix: 增加安全路径解析功能,防止路径穿越请求

This commit is contained in:
DrSmoothl
2026-03-14 22:22:06 +08:00
parent 172615f18a
commit 1978b097e3

View File

@@ -3,7 +3,7 @@
from importlib import import_module
from pathlib import Path
import mimetypes
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from src.common.logger import get_logger
@@ -11,6 +11,19 @@ from src.common.logger import get_logger
logger = get_logger("webui.app")
def _resolve_safe_static_file_path(static_path: Path, full_path: str) -> Path | None:
static_root = static_path.resolve()
try:
candidate_path = (static_root / full_path).resolve()
candidate_path.relative_to(static_root)
except (OSError, RuntimeError, ValueError):
logger.warning(f"🚫 检测到疑似路径穿越请求: {full_path}")
return None
return candidate_path
def create_app(
host: str = "0.0.0.0",
port: int = 8001,
@@ -136,8 +149,11 @@ def _setup_static_files(app: FastAPI):
response.headers["X-Robots-Tag"] = "noindex, nofollow, noarchive"
return response
file_path = static_path / full_path
if file_path.is_file() and file_path.exists():
file_path = _resolve_safe_static_file_path(static_path, full_path)
if file_path is None:
raise HTTPException(status_code=404, detail="Not Found")
if file_path.exists() and file_path.is_file():
media_type = mimetypes.guess_type(str(file_path))[0]
response = FileResponse(file_path, media_type=media_type)
if str(file_path).endswith(".html"):