repospace / backend /app /security /paths.py
2Btainment's picture
Initial RepoSpace MVP: FastAPI + constrained sandbox + React UI
3c07134 verified
Raw History Blame Contribute Delete
621 Bytes
"""Path safety helpers."""
from __future__ import annotations
from pathlib import Path
def is_within_directory(base: Path, target: Path) -> bool:
try:
base_r = base.resolve()
target_r = target.resolve()
return target_r == base_r or base_r in target_r.parents
except OSError:
return False
def safe_join(base: Path, *parts: str) -> Path:
"""Join and ensure result stays under base (no path traversal)."""
candidate = base.joinpath(*parts).resolve()
if not is_within_directory(base, candidate):
raise ValueError("path traversal blocked")
return candidate