Skip to content

_util

_util

Vendored utility functions for filesystem, templates, logging, naming, and sanitization.

__all__ = ['effective_ssh_key_name', 'ensure_dir', 'ensure_dir_writable', 'log_debug', 'log_warning', 'read_pidfile_safely', 'sanitize_tty', 'systemd_escape', 'systemd_exec_argv', 'systemd_user_unit_dir', 'unlink_pidfile_safely', 'warn_user', 'write_sensitive_file'] module-attribute

systemd_user_unit_dir()

Return the systemd user unit directory, validated against path traversal.

Refuses to run as root (euid == 0) and resolves $XDG_CONFIG_HOME to ensure the result stays beneath the user's home directory.

Raises SystemExit on validation failure.

Source code in src/terok_sandbox/_util/_fs.py
def systemd_user_unit_dir() -> Path:
    """Return the systemd user unit directory, validated against path traversal.

    Refuses to run as root (``euid == 0``) and resolves ``$XDG_CONFIG_HOME``
    to ensure the result stays beneath the user's home directory.

    Raises [`SystemExit`][SystemExit] on validation failure.
    """
    if os.geteuid() == 0:
        raise SystemExit(
            "Refusing to manage user systemd units as root. "
            "Run without sudo or use a system-level unit instead."
        )
    xdg = os.environ.get("XDG_CONFIG_HOME")
    config_home = Path(xdg).resolve() if xdg else Path.home() / ".config"
    home = Path.home().resolve()
    if not str(config_home).startswith(str(home)):
        raise SystemExit(
            f"XDG_CONFIG_HOME ({config_home}) resolves outside the home directory ({home}). "
            "Refusing to install systemd units to a potentially untrusted location."
        )
    return config_home / "systemd" / "user"

log_debug(message)

Append a DEBUG line to the sandbox's default log.

Source code in src/terok_sandbox/_util/_logging.py
def log_debug(message: str) -> None:
    """Append a DEBUG line to the sandbox's default log."""
    _default_logger.debug(message)

log_warning(message)

Append a WARNING line to the sandbox's default log.

Source code in src/terok_sandbox/_util/_logging.py
def log_warning(message: str) -> None:
    """Append a WARNING line to the sandbox's default log."""
    _default_logger.warning(message)

warn_user(component, message)

Print a structured warning to stderr and log it to the sandbox's default log.

Source code in src/terok_sandbox/_util/_logging.py
def warn_user(component: str, message: str) -> None:
    """Print a structured warning to stderr and log it to the sandbox's default log."""
    _default_logger.warn_user(component, message)

effective_ssh_key_name(scope, *, ssh_key_name=None, key_type='ed25519')

Return the SSH key filename to use.

Precedence
  1. Explicit ssh_key_name (from caller config)
  2. Derived default: id_<type>_<scope>
Source code in src/terok_sandbox/_util/_naming.py
def effective_ssh_key_name(
    scope: str, *, ssh_key_name: str | None = None, key_type: str = "ed25519"
) -> str:
    """Return the SSH key filename to use.

    Precedence:
      1. Explicit *ssh_key_name* (from caller config)
      2. Derived default: ``id_<type>_<scope>``
    """
    if ssh_key_name:
        return ssh_key_name
    algo = "ed25519" if key_type == "ed25519" else "rsa"
    return f"id_{algo}_{scope}"

read_pidfile_safely(pidfile)

Read a PID from pidfile without following symlinks.

Returns the integer PID on success, or None on any failure path (missing file, symlink, non-regular file, invalid contents).

Source code in src/terok_sandbox/_util/_pidfile.py
def read_pidfile_safely(pidfile: Path) -> int | None:
    """Read a PID from *pidfile* without following symlinks.

    Returns the integer PID on success, or ``None`` on any failure path
    (missing file, symlink, non-regular file, invalid contents).
    """
    nofollow = getattr(os, "O_NOFOLLOW", 0)
    try:
        fd = os.open(pidfile, os.O_RDONLY | nofollow)
    except OSError:
        # ``FileNotFoundError`` is an ``OSError`` subclass — one clause
        # covers both ENOENT and ELOOP/EACCES/etc.
        return None
    try:
        st = os.fstat(fd)
        if not stat.S_ISREG(st.st_mode):
            return None
        raw = os.read(fd, _MAX_PID_BYTES).decode("utf-8", errors="replace").strip()
    finally:
        os.close(fd)
    try:
        return int(raw)
    except ValueError:
        return None

Unlink pidfile only if it's a regular file (refusing symlinks).

The lstat check is what makes the difference: a plain Path.unlink() happily removes a symlink target, which is the file-clobber vector (CWE-59) the safe-handling guidance calls out. Any failure is silently ignored — this is cleanup, not a critical path.

Source code in src/terok_sandbox/_util/_pidfile.py
def unlink_pidfile_safely(pidfile: Path) -> None:
    """Unlink *pidfile* only if it's a regular file (refusing symlinks).

    The ``lstat`` check is what makes the difference: a plain
    ``Path.unlink()`` happily removes a symlink target, which is the
    file-clobber vector
    ([CWE-59](https://cwe.mitre.org/data/definitions/59.html)) the
    safe-handling guidance calls out.  Any failure is silently ignored
    — this is cleanup, not a critical path.
    """
    try:
        st = os.lstat(pidfile)
    except OSError:
        # ``FileNotFoundError`` is an ``OSError`` subclass — one clause
        # covers both the "already gone" common case and pathological
        # ``EACCES`` / parent-dir failures.
        return
    if not stat.S_ISREG(st.st_mode):
        return
    try:
        os.unlink(pidfile)
    except OSError:
        # Same subclass-relationship as above; one clause swallows the
        # full TOCTOU + EBUSY range.
        pass

systemd_escape(arg)

Escape arg for a systemd unit-file value position (e.g. ExecStart=).

Three systemd-parser hazards a POSIX-style quoter (shlex.join) handles wrong:

  • % introduces specifier expansion — escaped as %%.
  • Whitespace separates ExecStart= tokens. Systemd treats both space and tab as separators (per systemd.syntax(7)); escape both as \x20 / \x09 so a path containing either stays one argv element.

Common Python paths (/usr/bin/python3.12) round-trip unchanged. Atypical paths (pipx-on-macOS framework prefixes, multi-Python rootfs layouts with % in directory names, custom build trees with tabs in names) survive instead of silently mis-parsing.

Source code in src/terok_sandbox/_util/_templates.py
def systemd_escape(arg: str) -> str:
    """Escape *arg* for a systemd unit-file value position (e.g. ``ExecStart=``).

    Three systemd-parser hazards a POSIX-style quoter (``shlex.join``)
    handles wrong:

    - ``%`` introduces specifier expansion — escaped as ``%%``.
    - Whitespace separates ``ExecStart=`` tokens.  Systemd treats both
      space and tab as separators (per ``systemd.syntax(7)``); escape
      both as ``\\x20`` / ``\\x09`` so a path containing either stays
      one argv element.

    Common Python paths (``/usr/bin/python3.12``) round-trip unchanged.
    Atypical paths (pipx-on-macOS framework prefixes, multi-Python
    rootfs layouts with ``%`` in directory names, custom build trees
    with tabs in names) survive instead of silently mis-parsing.
    """
    return arg.replace("%", "%%").replace(" ", "\\x20").replace("\t", "\\x09")

systemd_exec_argv(prefix)

Join prefix into a single ExecStart= value, each element escaped.

Use this instead of :func:shlex.join for unit-file ExecStart, ExecStartPre, etc. — POSIX shell quoting and systemd unit quoting diverge enough that shlex.join mis-renders paths that contain % or whitespace.

Source code in src/terok_sandbox/_util/_templates.py
def systemd_exec_argv(prefix: Iterable[str]) -> str:
    """Join *prefix* into a single ``ExecStart=`` value, each element escaped.

    Use this instead of :func:`shlex.join` for unit-file ``ExecStart``,
    ``ExecStartPre``, etc. — POSIX shell quoting and systemd unit
    quoting diverge enough that ``shlex.join`` mis-renders paths that
    contain ``%`` or whitespace.
    """
    return " ".join(systemd_escape(arg) for arg in prefix)