"""The drafter's sandbox: an export of the tracked tree with no .git, compared afterwards. The drafter never runs in the repository. It edits a copy, and only the changes the caller allows are copied back, so a write to .git, a hook or any other path cannot reach the checkout the job commits from. """ from __future__ import annotations import hashlib import os import shutil import subprocess import tempfile from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from docs_review.git import GitError from docs_review.secrets import scrub_env from docs_review.tree import inside ARCHIVE_TIMEOUT_S = 300 def make_sandbox(env: Mapping[str, str]) -> Path: """A fresh empty directory under RUNNER_TEMP, or the system temp directory.""" parent = env.get("RUNNER_TEMP") if parent: return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-", dir=parent)) return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-")) def export_tree(cwd: Path, dest: Path) -> None: """`git archive HEAD | tar -x -C dest`: the tracked tree at HEAD, without .git.""" env = scrub_env(os.environ) archive = subprocess.Popen(["git", "archive", "--format=tar", "HEAD"], cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: tar = subprocess.run(["tar", "-x", "-f", "-", "-C", str(dest)], stdin=archive.stdout, env=env, capture_output=True, timeout=ARCHIVE_TIMEOUT_S, check=False) finally: archive.stdout.close() archive_err = archive.stderr.read().decode("utf-8", "replace") archive.stderr.close() archive.wait() if archive.returncode != 0: raise GitError(f"git archive HEAD failed: {archive_err.strip()}") if tar.returncode != 0: raise GitError(f"tar -x failed: {tar.stderr.decode('utf-8', 'replace').strip()}") def remove_symlinks(root: Path) -> tuple[str, ...]: """Delete every symlink under root, so the drafter's Edit and Write cannot follow one out of the sandbox. Returns the removed paths.""" removed = [] for dirpath, dirnames, filenames in os.walk(root): base = Path(dirpath) for name in list(filenames) + list(dirnames): path = base / name if path.is_symlink(): path.unlink() removed.append(path.relative_to(root).as_posix()) dirnames[:] = [d for d in dirnames if (base / d).is_dir()] return tuple(sorted(removed)) class CopyRefused(RuntimeError): """A change cannot be copied back safely; the message names the path.""" def _digest(path: Path) -> str: """A content hash; a symlink hashes its target text and is marked as a link.""" if path.is_symlink(): return "link:" + os.readlink(path) h = hashlib.sha256() with path.open("rb") as fh: for chunk in iter(lambda: fh.read(1 << 16), b""): h.update(chunk) return "file:" + h.hexdigest() def snapshot(root: Path) -> dict[str, str]: """Every file (and symlink) under root, as repository-relative POSIX path -> hash.""" out: dict[str, str] = {} for dirpath, dirnames, filenames in os.walk(root): base = Path(dirpath) names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()] for name in names: path = base / name out[path.relative_to(root).as_posix()] = _digest(path) return out @dataclass(frozen=True) class TreeChange: new: tuple[str, ...] changed: tuple[str, ...] deleted: tuple[str, ...] @property def paths(self) -> tuple[str, ...]: return tuple(sorted(self.new + self.changed + self.deleted)) def compare(before: Mapping[str, str], after: Mapping[str, str]) -> TreeChange: return TreeChange( new=tuple(sorted(set(after) - set(before))), changed=tuple(sorted(p for p in set(after) & set(before) if after[p] != before[p])), deleted=tuple(sorted(set(before) - set(after))), ) def is_regular(sandbox: Path, rel: str) -> bool: path = sandbox / rel return path.is_file() and not path.is_symlink() def _safe_target(cwd: Path, rel: str) -> Path: """cwd/rel, refusing .git, a symlink at or above the destination, or a destination that resolves outside cwd.""" parts = Path(rel).parts if not parts or ".git" in parts or ".." in parts or Path(rel).is_absolute(): raise CopyRefused(rel) current = cwd for part in parts: current = current / part if current.is_symlink(): raise CopyRefused(rel) target = cwd / rel if not inside(cwd, target): raise CopyRefused(rel) return target def copy_back(change: TreeChange, sandbox: Path, cwd: Path) -> None: """Apply the sandbox's new, changed and deleted files to cwd. Every source and target is checked before any is written, so a refusal leaves cwd untouched.""" for rel in change.new + change.changed: if not is_regular(sandbox, rel): raise CopyRefused(rel) writes = [(sandbox / rel, _safe_target(cwd, rel)) for rel in change.new + change.changed] deletes = [_safe_target(cwd, rel) for rel in change.deleted] for source, target in writes: target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(source, target) for target in deletes: if target.exists(): target.unlink() def remove(path: Path | None) -> None: if path is not None: shutil.rmtree(path, ignore_errors=True)