"""Confined reads for the import scripts.
Every importer in this directory turns files from somewhere else (an upstream
clone, the vault) into content this repository publishes. A plain ``open()`` or
``shutil.copy`` follows symbolic links, so a link planted in the source — a
``LICENSE`` pointing at ``~/.ssh/id_ed25519``, a ``notes.md`` pointing at the
runner's ``.git/config`` — would be read with the importer's privileges and
written straight into the public tree.
The helpers here refuse that. A source path is accepted only when
* it sits under the declared root,
* no component between the root and the file is a symbolic link,
* the file itself is a regular file, not a link, device, socket or FIFO, and
* its resolved location is still inside the resolved root.
The root itself may be reached through a link (``~/git`` often is); only what
lies below it is the untrusted part. The final open uses ``O_NOFOLLOW`` and
re-checks the descriptor, so swapping the file for a link between the check and
the read does not get through either.
Importers validate every path they are going to read *before* they delete or
write anything, so a rejected source leaves the existing output untouched.
"""
from __future__ import annotations
import os
import shutil
import stat
class UnsafeSource(Exception):
"""A source path is a link, leaves its root, or is not a regular file."""
def _components(root: str, path: str) -> list[str]:
root_abs = os.path.abspath(root)
path_abs = os.path.abspath(path)
rel = os.path.relpath(path_abs, root_abs)
if rel == os.curdir or rel == os.pardir or rel.startswith(os.pardir + os.sep) or os.path.isabs(rel):
raise UnsafeSource(f"{path_abs} is not inside {root_abs}")
return rel.split(os.sep)
def check_dir(root, path) -> str:
"""Return ``path`` if it is a real directory under ``root`` with no linked component."""
root, path = os.fspath(root), os.fspath(path)
current = os.path.abspath(root)
for part in _components(root, path):
current = os.path.join(current, part)
if os.path.islink(current):
raise UnsafeSource(f"refusing symbolic link in source: {current}")
if not stat.S_ISDIR(os.lstat(current).st_mode):
raise UnsafeSource(f"not a directory: {current}")
return current
def check_file(root, path) -> str:
"""Return ``path`` if it is a regular file under ``root`` with no linked component."""
root, path = os.fspath(root), os.fspath(path)
current = os.path.abspath(root)
for part in _components(root, path):
current = os.path.join(current, part)
if os.path.islink(current):
raise UnsafeSource(f"refusing symbolic link in source: {current}")
if not stat.S_ISREG(os.lstat(current).st_mode):
raise UnsafeSource(f"not a regular file: {current}")
root_real = os.path.realpath(root)
if os.path.commonpath([root_real, os.path.realpath(current)]) != root_real:
raise UnsafeSource(f"{current} resolves outside {root_real}")
return current
def is_safe_file(root, path) -> bool:
"""True when ``check_file`` would accept ``path``. A missing file is simply False."""
try:
check_file(root, path)
except (UnsafeSource, OSError):
return False
return True
def is_link(path) -> bool:
return os.path.islink(os.fspath(path))
def open_binary(root, path):
"""Open a confined regular file for reading. The caller closes it."""
checked = check_file(root, path)
fd = os.open(checked, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise UnsafeSource(f"not a regular file: {checked}")
return os.fdopen(fd, "rb")
except BaseException:
os.close(fd)
raise
def read_bytes(root, path) -> bytes:
with open_binary(root, path) as handle:
return handle.read()
def read_text(root, path, errors: str = "strict") -> str:
return read_bytes(root, path).decode("utf-8", errors=errors)
def copy_file(root, path, destination) -> None:
"""Copy a confined regular file's bytes. Never follows a link on either side."""
destination = os.fspath(destination)
with open_binary(root, path) as source:
if os.path.islink(destination):
os.unlink(destination)
with open(destination, "wb") as target:
shutil.copyfileobj(source, target, 1024 * 1024)