validatePath 验证路径安全性 参考: deepagents/filesystem.py:87-129
(path string)
| 232 | // validatePath 验证路径安全性 |
| 233 | // 参考: deepagents/filesystem.py:87-129 |
| 234 | func (m *FilesystemMiddleware) validatePath(path string) (string, error) { |
| 235 | if !m.enablePathValidation { |
| 236 | return path, nil |
| 237 | } |
| 238 | |
| 239 | // 1. 检查路径遍历攻击 |
| 240 | if strings.Contains(path, "..") { |
| 241 | return "", fmt.Errorf("路径遍历不允许(包含 '..'): %s", path) |
| 242 | } |
| 243 | |
| 244 | if strings.HasPrefix(path, "~") { |
| 245 | return "", fmt.Errorf("路径遍历不允许(以 '~' 开头): %s", path) |
| 246 | } |
| 247 | |
| 248 | // 2. 规范化路径 |
| 249 | normalized := filepath.Clean(path) |
| 250 | // 转换为 Unix 风格路径(统一使用 /) |
| 251 | normalized = filepath.ToSlash(normalized) |
| 252 | |
| 253 | // 3. 确保路径以 / 开头 |
| 254 | if !strings.HasPrefix(normalized, "/") { |
| 255 | normalized = "/" + normalized |
| 256 | } |
| 257 | |
| 258 | // 4. 检查允许的前缀 |
| 259 | if len(m.allowedPathPrefixes) > 0 { |
| 260 | allowed := false |
| 261 | for _, prefix := range m.allowedPathPrefixes { |
| 262 | // 规范化前缀(去掉尾部斜杠) |
| 263 | normalizedPrefix := filepath.Clean(prefix) |
| 264 | normalizedPrefix = filepath.ToSlash(normalizedPrefix) |
| 265 | if !strings.HasPrefix(normalizedPrefix, "/") { |
| 266 | normalizedPrefix = "/" + normalizedPrefix |
| 267 | } |
| 268 | |
| 269 | // 检查前缀匹配(normalized == prefix 或 normalized 在 prefix 下) |
| 270 | if normalized == normalizedPrefix || strings.HasPrefix(normalized, normalizedPrefix+"/") { |
| 271 | allowed = true |
| 272 | break |
| 273 | } |
| 274 | } |
| 275 | if !allowed { |
| 276 | return "", fmt.Errorf("路径必须以以下前缀之一开头 %v: %s", m.allowedPathPrefixes, normalized) |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | return normalized, nil |
| 281 | } |
no outgoing calls