mirror of
https://github.com/Mintplex-Labs/langchain-python.git
synced 2026-08-27 09:21:30 -04:00
4adfd790f0
- Permit the specification of a `root_dir` to the read/write file tools to specify a working directory - Add validation for attempts to read/write outside the directory (e.g., through `../../` or symlinks or `/abs/path`'s that don't lie in the correct path) - Add some tests for all One question is whether we should make a default root directory for these? tradeoffs either way
27 lines
908 B
Python
27 lines
908 B
Python
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
def is_relative_to(path: Path, root: Path) -> bool:
|
|
"""Check if path is relative to root."""
|
|
if sys.version_info >= (3, 9):
|
|
# No need for a try/except block in Python 3.8+.
|
|
return path.is_relative_to(root)
|
|
try:
|
|
path.relative_to(root)
|
|
return True
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def get_validated_relative_path(root: Path, user_path: str) -> Path:
|
|
"""Resolve a relative path, raising an error if not within the root directory."""
|
|
# Note, this still permits symlinks from outside that point within the root.
|
|
# Further validation would be needed if those are to be disallowed.
|
|
root = root.resolve()
|
|
full_path = (root / user_path).resolve()
|
|
|
|
if not is_relative_to(full_path, root):
|
|
raise ValueError(f"Path {user_path} is outside of the allowed directory {root}")
|
|
return full_path
|