128 lines
4.7 KiB
Python
128 lines
4.7 KiB
Python
"""
|
||||
|
|
路径安全守卫
|
|||
|
|
============
|
|||
|
|
|
|||
|
|
【功能说明】
|
|||
|
|
统一校验文件路径是否在允许的操作范围内,杜绝 Agent 越权读写系统文件。
|
|||
|
|
是整个工具层的「安全第一道闸门」。
|
|||
|
|
|
|||
|
|
【技术选型理由】
|
|||
|
|
1. 白名单根目录(默认 D:\\Agent\\code):决策点 3 已定代码集中在该目录,
|
|||
|
|
工具只允许在此范围内操作,硬约束 6「全落 D 盘」在路径层强制。
|
|||
|
|
2. resolve() 后再比对:防 `..\\..\\Windows` 路径穿越攻击,
|
|||
|
|
以及符号链接逃逸(Windows 下 junction/symlink 同理)。
|
|||
|
|
3. 校验函数独立成模块:所有工具(file/executor/git)共用同一套规则,
|
|||
|
|
避免各写一套校验导致漏网之鱼。
|
|||
|
|
|
|||
|
|
【实现思路】
|
|||
|
|
- PathGuard 持有 allowed_roots 列表;
|
|||
|
|
- 校验时先 resolve() 为绝对路径,再判断是否位于任一根目录之下;
|
|||
|
|
- 提供 ensure_under_root() 便捷函数,工具层一行调用。
|
|||
|
|
|
|||
|
|
【潜在风险与应对】
|
|||
|
|
风险1:allowed_roots 配置过宽(如允许整个 D 盘)。
|
|||
|
|
应对:默认只允许 D:\\Agent\\code 与 D:\\Agent\\agent\\data,
|
|||
|
|
其他路径需在配置里显式追加。
|
|||
|
|
风险2:符号链接指向根目录之外。
|
|||
|
|
应对:resolve() 会解析符号链接到真实路径,再做前缀比对。
|
|||
|
|
风险3:大小写差异导致比对失败(Windows 不区分大小写)。
|
|||
|
|
应对:统一转小写后再比对。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import logging
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.tools.path_guard")
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PathSecurityError(PermissionError):
|
|||
|
|
"""路径越权访问异常(中文可读)"""
|
|||
|
|
|
|||
|
|
def __init__(self, message: str) -> None:
|
|||
|
|
super().__init__(message)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PathGuard:
|
|||
|
|
"""路径安全守卫:限定工具可操作的根目录范围"""
|
|||
|
|
|
|||
|
|
def __init__(self, allowed_roots: list[Path]) -> None:
|
|||
|
|
# 统一 resolve 为真实绝对路径,比对时用小写规避大小写差异
|
|||
|
|
self._roots = [Path(r).expanduser().resolve() for r in allowed_roots]
|
|||
|
|
logger.info("路径守卫初始化,允许根目录:%s", self._roots)
|
|||
|
|
|
|||
|
|
def is_allowed(self, path: Path, *, readonly: bool = False) -> bool:
|
|||
|
|
"""
|
|||
|
|
判断路径是否在允许范围内。
|
|||
|
|
|
|||
|
|
【策略】
|
|||
|
|
- readonly=True(读取/搜索):允许任意本地目录(用户要求);
|
|||
|
|
- readonly=False(写入/删除/执行):仍限定白名单根目录。
|
|||
|
|
"""
|
|||
|
|
try:
|
|||
|
|
resolved = Path(path).expanduser().resolve()
|
|||
|
|
except OSError:
|
|||
|
|
return False
|
|||
|
|
# 拒绝 UNC 网络路径(防止误操作远程共享)
|
|||
|
|
if str(resolved).startswith("\\\\"):
|
|||
|
|
return False
|
|||
|
|
if readonly:
|
|||
|
|
return True
|
|||
|
|
# 写入/删除:仍走白名单
|
|||
|
|
resolved_lower = str(resolved).lower()
|
|||
|
|
return any(
|
|||
|
|
resolved_lower == str(root).lower()
|
|||
|
|
or resolved_lower.startswith(str(root).lower() + "\\")
|
|||
|
|
or resolved_lower.startswith(str(root).lower() + "/")
|
|||
|
|
for root in self._roots
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
def ensure_allowed(self, path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
|||
|
|
"""
|
|||
|
|
校验路径合法性,不合法抛 PathSecurityError。
|
|||
|
|
|
|||
|
|
【返回】解析后的绝对路径(后续工具可直接使用)。
|
|||
|
|
"""
|
|||
|
|
resolved = Path(path).expanduser().resolve()
|
|||
|
|
if not self.is_allowed(resolved, readonly=readonly):
|
|||
|
|
raise PathSecurityError(
|
|||
|
|
f"拒绝{action}:路径 {resolved} 不在允许的操作范围内 "
|
|||
|
|
f"(允许根目录:{[str(r) for r in self._roots]})"
|
|||
|
|
)
|
|||
|
|
return resolved
|
|||
|
|
|
|||
|
|
|
|||
|
|
# ---------- 默认守卫(工具层统一使用)----------
|
|||
|
|
|
|||
|
|
_default_guard: PathGuard | None = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_default_guard() -> PathGuard:
|
|||
|
|
"""
|
|||
|
|
获取默认路径守卫。
|
|||
|
|
|
|||
|
|
【允许范围】全部 D 盘 + 常见项目目录(用户要求 Agent 可读取任意目录)。
|
|||
|
|
"""
|
|||
|
|
global _default_guard
|
|||
|
|
if _default_guard is None:
|
|||
|
|
_default_guard = PathGuard(
|
|||
|
|
allowed_roots=[
|
|||
|
|
Path(r"D:\Agent\code"),
|
|||
|
|
Path(r"D:\Agent\agent\data"),
|
|||
|
|
Path(r"D:\Agent\pytest_tmp"),
|
|||
|
|
Path(r"D:\Project"),
|
|||
|
|
Path(r"D:\Code"),
|
|||
|
|
Path(r"D:\Workspace"),
|
|||
|
|
Path(r"D:\Work"),
|
|||
|
|
Path(r"D:\Git"),
|
|||
|
|
Path("D:\\"),
|
|||
|
|
]
|
|||
|
|
)
|
|||
|
|
return _default_guard
|
|||
|
|
|
|||
|
|
|
|||
|
|
def ensure_under_root(path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
|||
|
|
"""便捷函数:校验路径并返回解析后的绝对路径。"""
|
|||
|
|
return get_default_guard().ensure_allowed(path, action, readonly=readonly)
|