From e12ef234784cbc9e5811bc9211952437af7be75a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Sun, 29 Nov 2026 15:18:18 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(discovery):=20don't=20hang?= =?UTF-8?q?=20on=20FIFO=20version=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shim resolution checks that a .python-version path is a file, then opens it by name. Another local user who can write to a shared parent directory can swap in a FIFO between those two calls, and open() then waits for a writer with no timeout to bound the wait, hanging discovery. Open version files with O_NONBLOCK and check the descriptor that is read, skipping anything that is not a regular file. O_NOFOLLOW is not used, so symlinked version files keep working. Reported by oss-scanner as ANT-2026-2XCH1H5T. --- .../changelog/+version-file-fifo.security.rst | 2 ++ docs/explanation.rst | 4 +-- src/python_discovery/_discovery.py | 30 +++++++++++++------ tests/python_discovery/test_discovery.py | 21 +++++++++++++ 4 files changed, 46 insertions(+), 11 deletions(-) create mode 100644 docs/changelog/+version-file-fifo.security.rst diff --git a/docs/changelog/+version-file-fifo.security.rst b/docs/changelog/+version-file-fifo.security.rst new file mode 100644 index 0000000..bd54aed --- /dev/null +++ b/docs/changelog/+version-file-fifo.security.rst @@ -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. diff --git a/docs/explanation.rst b/docs/explanation.rst index 403f532..6168876 100644 --- a/docs/explanation.rst +++ b/docs/explanation.rst @@ -72,8 +72,8 @@ detects these shims and resolves them to the actual binary. `mise `_ and `asdf `_ 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. diff --git a/src/python_discovery/_discovery.py b/src/python_discovery/_discovery.py index 00a70c2..fc39859 100644 --- a/src/python_discovery/_discovery.py +++ b/src/python_discovery/_discovery.py @@ -10,6 +10,7 @@ import logging import os +import stat import sys from contextlib import suppress from dataclasses import dataclass @@ -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): ... diff --git a/tests/python_discovery/test_discovery.py b/tests/python_discovery/test_discovery.py index a6f6885..6063142 100644 --- a/tests/python_discovery/test_discovery.py +++ b/tests/python_discovery/test_discovery.py @@ -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 @@ -22,6 +23,7 @@ _active_versions, _read_python_version_file, _resolve_shim, + _versions_in_file, get_paths, path_exe_finder, propose_interpreters, @@ -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