path_security.py 1.1 KB

123456789101112131415161718192021222324252627282930
  1. """Shared path validation helpers for tool implementations (skills, cron, credential files)."""
  2. import re
  3. from pathlib import Path
  4. from typing import Optional
  5. def validate_within_dir(path: Path, root: Path) -> Optional[str]:
  6. """Error message if *path* does not resolve inside *root* (symlinks and ``..`` followed)."""
  7. try:
  8. path.resolve().relative_to(root.resolve())
  9. except (ValueError, OSError) as exc:
  10. return f"Path escapes allowed directory: {exc}"
  11. return None
  12. def has_traversal_component(path_str: str) -> bool:
  13. """Cheap pre-check for a literal ``..`` component before full resolution."""
  14. return ".." in Path(path_str).parts
  15. # Control chars + Unicode line separators (NEL, LS, PS): newline-bearing paths are legal POSIX
  16. # names, but they corrupt line-delimited protocols (MEDIA: tags) and forge log lines. Same
  17. # class as _LOG_UNSAFE_CHARS in gateway.platforms.base.
  18. _UNSAFE_PATH_CHARS = re.compile(r"[\x00-\x1f\x7f\x85\u2028\u2029]")
  19. def has_unsafe_path_chars(path_str: str) -> bool:
  20. """True when *path_str* contains control characters or line separators."""
  21. return bool(_UNSAFE_PATH_CHARS.search(path_str))