|
| 1 | +"""Canonicalise and bound filesystem paths that arrive from a CLI argument. |
| 2 | +
|
| 3 | +The ``python -m je_auto_control...`` entry points take output/input paths from |
| 4 | +``argv``. A mistaken — or generated — argument such as ``../../etc/passwd`` |
| 5 | +would otherwise be handed straight to ``write_text``/``mkdir``. Every such |
| 6 | +path goes through :func:`validate_path` first: it is canonicalised with |
| 7 | +``os.path.realpath`` (so ``..`` and symlinks are resolved before the check) |
| 8 | +and must land inside one of the allowed roots. |
| 9 | +
|
| 10 | +The default roots are the current working directory, the user's home and the |
| 11 | +system temp directory — the places an operator actually exports to. Set |
| 12 | +``AUTOCONTROL_ALLOWED_PATH_ROOTS`` (``os.pathsep``-separated) to add more, for |
| 13 | +example a mounted volume in a container. |
| 14 | +
|
| 15 | +Headless module: imports no PySide6. |
| 16 | +""" |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import os |
| 20 | +import tempfile |
| 21 | +from pathlib import Path |
| 22 | +from typing import Iterable, List, Optional, Sequence |
| 23 | + |
| 24 | +from je_auto_control.utils.exception.exceptions import AutoControlException |
| 25 | + |
| 26 | +ALLOWED_ROOTS_ENV = "AUTOCONTROL_ALLOWED_PATH_ROOTS" |
| 27 | + |
| 28 | + |
| 29 | +class PathNotAllowedError(AutoControlException): |
| 30 | + """A supplied path is malformed or resolves outside the allowed roots.""" |
| 31 | + |
| 32 | + |
| 33 | +def default_allowed_roots() -> List[Path]: |
| 34 | + """Return the roots a CLI path may resolve into, extras from env first.""" |
| 35 | + roots: List[Path] = [] |
| 36 | + for entry in os.environ.get(ALLOWED_ROOTS_ENV, "").split(os.pathsep): |
| 37 | + if entry.strip(): |
| 38 | + roots.append(_canonical(entry.strip())) |
| 39 | + roots.append(_canonical(Path.cwd())) |
| 40 | + roots.append(_canonical(Path.home())) |
| 41 | + roots.append(_canonical(tempfile.gettempdir())) |
| 42 | + return roots |
| 43 | + |
| 44 | + |
| 45 | +def validate_path(raw: os.PathLike | str, *, |
| 46 | + allowed_roots: Optional[Iterable[os.PathLike | str]] = None, |
| 47 | + allowed_suffixes: Optional[Sequence[str]] = None, |
| 48 | + must_exist: bool = False) -> Path: |
| 49 | + """Return ``raw`` canonicalised, or raise :class:`PathNotAllowedError`. |
| 50 | +
|
| 51 | + ``allowed_suffixes`` is matched case-insensitively against the final |
| 52 | + suffix. ``must_exist`` additionally requires the resolved path to be |
| 53 | + present on disk. |
| 54 | + """ |
| 55 | + text = os.fspath(raw) |
| 56 | + if not text or "\x00" in text: |
| 57 | + raise PathNotAllowedError(f"invalid path: {text!r}") |
| 58 | + candidate = _canonical(text) |
| 59 | + _check_suffix(candidate, allowed_suffixes) |
| 60 | + roots = default_allowed_roots() if allowed_roots is None \ |
| 61 | + else [_canonical(root) for root in allowed_roots] |
| 62 | + if not any(_is_within(candidate, root) for root in roots): |
| 63 | + raise PathNotAllowedError( |
| 64 | + f"{candidate} is outside the allowed roots " |
| 65 | + f"({', '.join(str(root) for root in roots)}); " |
| 66 | + f"set {ALLOWED_ROOTS_ENV} to permit it") |
| 67 | + if must_exist and not candidate.exists(): |
| 68 | + raise PathNotAllowedError(f"{candidate} does not exist") |
| 69 | + return candidate |
| 70 | + |
| 71 | + |
| 72 | +# --- internals ---------------------------------------------------- |
| 73 | + |
| 74 | +def _canonical(value: os.PathLike | str) -> Path: |
| 75 | + return Path(os.path.realpath(Path(value).expanduser())) |
| 76 | + |
| 77 | + |
| 78 | +def _check_suffix(candidate: Path, |
| 79 | + allowed_suffixes: Optional[Sequence[str]]) -> None: |
| 80 | + if not allowed_suffixes: |
| 81 | + return |
| 82 | + wanted = {suffix.lower() for suffix in allowed_suffixes} |
| 83 | + if candidate.suffix.lower() not in wanted: |
| 84 | + raise PathNotAllowedError( |
| 85 | + f"{candidate.name} does not end in {' / '.join(sorted(wanted))}") |
| 86 | + |
| 87 | + |
| 88 | +def _is_within(candidate: Path, root: Path) -> bool: |
| 89 | + return candidate == root or root in candidate.parents |
0 commit comments