Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changelog/+version-file-fifo.security.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Shim resolution no longer hangs when a ``.python-version`` file in a parent directory is replaced by a FIFO.
Version files are now opened without blocking and skipped unless they are regular files.
4 changes: 2 additions & 2 deletions docs/explanation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ detects these shims and resolves them to the actual binary.

`mise <https://mise.jdx.dev/>`_ and `asdf <https://asdf-vm.com/>`_ work similarly, using the
``MISE_DATA_DIR`` and ``ASDF_DATA_DIR`` environment variables to locate their installations.
python-discovery skips version files over 4096 characters. It checks parent directories and, for pyenv, the global
version when needed.
python-discovery skips version files over 4096 characters and paths that are not regular files, such as a FIFO. It
checks parent directories and, for pyenv, the global version when needed.

Version-file search starts in the current directory. If the process can no longer name that directory,
python-discovery starts from ``PWD`` in the supplied environment. If that is unavailable, it checks the global version.
Expand Down
30 changes: 21 additions & 9 deletions src/python_discovery/_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import logging
import os
import stat
import sys
from contextlib import suppress
from dataclasses import dataclass
Expand Down Expand Up @@ -326,18 +327,29 @@ def _read_python_version_file(start: str | Path, *, search_parents: bool = True)

def _versions_in_file(path: str | Path) -> list[str]:
try:
# pyenv reads raw bytes, so a byte that is not UTF-8 (a Latin-1 comment, say) must not hide the versions
with Path(path).open(encoding="utf-8", errors="replace") as fh:
# Version files can sit in shared parent directories; bound the in-process read.
max_chars = 4096
content = fh.read(max_chars + 1)
if len(content) > max_chars:
_LOGGER.debug("ignored oversized version file %s", path)
return []
return [v for line in content.split("\n") if (v := line.strip()) and not v.startswith("#")]
content = _read_version_file(path)
except OSError: # skip a file we cannot read, the same as one that names no version
_LOGGER.debug("failed to read %s", path, exc_info=True)
return []
if content is None:
return []
return [v for line in content.split("\n") if (v := line.strip()) and not v.startswith("#")]


def _read_version_file(path: str | Path) -> str | None:
# the path can be swapped for a FIFO after the isfile() check, and open() would then wait for a writer forever
# pyenv reads raw bytes, so a byte that is not UTF-8 (a Latin-1 comment, say) must not hide the versions
with os.fdopen(os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)), encoding="utf-8", errors="replace") as fh:
if not stat.S_ISREG(os.fstat(fh.fileno()).st_mode):
_LOGGER.debug("ignored special version file %s", path)
return None
# Version files can sit in shared parent directories; bound the in-process read.
max_chars = 4096
content = fh.read(max_chars + 1)
if len(content) > max_chars:
_LOGGER.debug("ignored oversized version file %s", path)
return None
return content


class PathPythonInfo(PythonInfo): ...
Expand Down
21 changes: 21 additions & 0 deletions tests/python_discovery/test_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import shutil
import stat
import sys
import threading
from copy import deepcopy
from pathlib import Path
from subprocess import check_call, check_output
Expand All @@ -22,6 +23,7 @@
_active_versions,
_read_python_version_file,
_resolve_shim,
_versions_in_file,
get_paths,
path_exe_finder,
propose_interpreters,
Expand Down Expand Up @@ -1378,6 +1380,25 @@ def test_read_python_version_file_empty_versions(tmp_path: Path) -> None:
assert result is None


@pytest.mark.skipif(sys.platform == "win32", reason="POSIX FIFOs")
def test_versions_in_file_skips_fifo(tmp_path: Path) -> None:
# a writer that never closes makes an unfixed read wait forever, so the call runs in a thread with a deadline
os.mkfifo(version_file := tmp_path / ".python-version")
reader = os.open(version_file, os.O_RDONLY | os.O_NONBLOCK)
writer = os.open(version_file, os.O_WRONLY | os.O_NONBLOCK)
os.write(writer, b"3.12\n")
results: list[list[str]] = []
worker = threading.Thread(target=lambda: results.append(_versions_in_file(version_file)))
try:
worker.start()
worker.join(timeout=10)
assert results == [[]]
finally:
os.close(writer)
os.close(reader)
worker.join()


def test_get_interpreter_multi_spec_all_fail(session_cache: DiskCache) -> None:
result = get_interpreter(["magic-one", "magic-two"], cache=session_cache)
assert result is None
Expand Down