mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2025-12-15 14:22:55 +08:00
✨ 优化路径验证功能,增加对非法字符和路径长度的检查,确保用户输入的路径更加安全
This commit is contained in:
parent
07ba035db6
commit
4d6d47bf8d
@ -42,14 +42,28 @@ def validate_path(path_str: str | None) -> tuple[Path | None, str | None]:
|
||||
if not path_str:
|
||||
return Path().resolve(), None
|
||||
|
||||
# 移除任何可能的路径遍历尝试
|
||||
# 1. 移除任何可能的路径遍历尝试
|
||||
path_str = re.sub(r"[\\/]\.\.[\\/]", "", path_str)
|
||||
# 规范化路径
|
||||
|
||||
# 2. 规范化路径并转换为绝对路径
|
||||
path = Path(path_str).resolve()
|
||||
# 验证路径是否在项目根目录内
|
||||
if not path.is_relative_to(Path().resolve()):
|
||||
return None, "访问路径超出允许范围"
|
||||
return path, None
|
||||
|
||||
# 3. 获取项目根目录
|
||||
root_dir = Path().resolve()
|
||||
|
||||
# 4. 验证路径是否在项目根目录内
|
||||
try:
|
||||
if not path.is_relative_to(root_dir):
|
||||
return None, "访问路径超出允许范围"
|
||||
except ValueError:
|
||||
return None, "无效的路径格式"
|
||||
|
||||
# 5. 验证路径是否包含任何危险字符
|
||||
if any(c in str(path) for c in ["..", "~", "*", "?", ">", "<", "|", '"']):
|
||||
return None, "路径包含非法字符"
|
||||
|
||||
# 6. 验证路径长度是否合理
|
||||
return (None, "路径长度超出限制") if len(str(path)) > 4096 else (path, None)
|
||||
except Exception as e:
|
||||
return None, f"路径验证失败: {e!s}"
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user