From 34ab9f567ba501fba078d8a22b2378ca86bc23c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Sun, 29 Nov 2026 15:14:47 -0800 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20fix(cache):=20reject=20untru?= =?UTF-8?q?sted=20lock=20directory?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DiskContentStore.locked() creates locks-v2 with mkdir(exist_ok=True), which accepts a symlink or a directory owned by another user. A lock taken there could stall lookups, and the lock file could be created outside the cache. Check the lock folder with the same rule _trusted_folder applies to the cache directories: a real directory owned by the current user or root and not writable by others. In a group-shared cache any real directory is accepted, as before, but a symlink is refused. A rejected folder logs a warning and the lookup continues without the cache. Fixes #285. Reported by oss-scanner as ANT-2026-RMWOKI09. --- docs/changelog/285.bugfix.rst | 3 ++ docs/explanation.rst | 8 +++-- src/python_discovery/_cache.py | 22 ++++++++++---- tests/python_discovery/test_cache.py | 30 +++++++++++++++++++ tests/python_discovery/test_cached_py_info.py | 14 +++++++++ 5 files changed, 68 insertions(+), 9 deletions(-) create mode 100644 docs/changelog/285.bugfix.rst diff --git a/docs/changelog/285.bugfix.rst b/docs/changelog/285.bugfix.rst new file mode 100644 index 0000000..be6a727 --- /dev/null +++ b/docs/changelog/285.bugfix.rst @@ -0,0 +1,3 @@ +``DiskCache`` no longer takes its locks in a ``locks-v2`` directory that is a symbolic link, belongs to another user, or +is writable by others. Discovery logs a warning and queries the interpreter without the cache instead, so a lock +directory left behind by another user can no longer block discovery or create lock files outside the cache. diff --git a/docs/explanation.rst b/docs/explanation.rst index 403f532..4e4a9ed 100644 --- a/docs/explanation.rst +++ b/docs/explanation.rst @@ -295,9 +295,11 @@ private directory for the cache root, including when callers share a machine. A relative cache root refers to the current directory when ``DiskCache`` is created. -On POSIX, lock files live in a restricted directory under the checked cache directory. Older releases use the previous -lock files, so processes running different releases do not coordinate cache writes. Use separate cache roots while both -run. +On POSIX, lock files live in a ``locks-v2`` directory under the checked cache directory. Discovery uses it only when it +is a real directory that is owned by the current user or root and not writable by others, unless the cache directory is +group-writable; otherwise it logs a warning and queries the interpreter without the cache. Older releases use the +previous lock files, so processes running different releases do not coordinate cache writes. Use separate cache roots +while both run. Subprocess timeout behavior ---------------------------- diff --git a/src/python_discovery/_cache.py b/src/python_discovery/_cache.py index d19e534..20ede07 100644 --- a/src/python_discovery/_cache.py +++ b/src/python_discovery/_cache.py @@ -110,7 +110,6 @@ def py_info(self, path: Path) -> ContentStore: def _trusted_folder(self) -> bool: if not hasattr(os, "geteuid"): return True - user_id = os.geteuid() folder = self._py_info_dir private = {self._root, folder.parent, folder} for candidate in (*reversed(folder.parents), folder): @@ -123,11 +122,8 @@ def _trusted_folder(self) -> bool: except OSError: _LOGGER.warning("not caching in %s", candidate, exc_info=True) return False - if ( - not stat.S_ISDIR(status.st_mode) - or status.st_uid not in {user_id, 0} - or (status.st_mode & 0o022 and (candidate in private or not status.st_mode & stat.S_ISVTX)) - ): + writable_ok = candidate not in private and bool(status.st_mode & stat.S_ISVTX) + if not _trusted_directory(status, writable_ok=writable_ok): _LOGGER.warning("not caching in untrusted directory %s", candidate) return False return True @@ -248,6 +244,12 @@ def locked(self) -> Generator[None]: group_shared = bool(self._folder.stat().st_mode & stat.S_IWGRP) lock_folder = self._folder / "locks-v2" lock_folder.mkdir(mode=0o770 if group_shared else 0o700, exist_ok=True) + # a group-shared cache is written by its members, so the lock folder may belong to another of them + status = lock_folder.lstat() + if not (stat.S_ISDIR(status.st_mode) if group_shared else _trusted_directory(status, writable_ok=False)): + _LOGGER.warning("not locking in untrusted directory %s", lock_folder) + msg = f"untrusted lock directory {lock_folder}" + raise PermissionError(msg) lock = FileLock(str(lock_folder / f"{self._key}.lock"), mode=0o660 if group_shared else 0o600) else: lock = FileLock(str(self._folder / f"{self._key}.lock")) @@ -255,6 +257,14 @@ def locked(self) -> Generator[None]: yield +def _trusted_directory(status: os.stat_result, *, writable_ok: bool) -> bool: + return ( + stat.S_ISDIR(status.st_mode) + and status.st_uid in {os.geteuid(), 0} + and (writable_ok or not status.st_mode & 0o022) + ) + + class NoOpCache(PyInfoCache): # Cache that does nothing -- implements PyInfoCache protocol. def py_info(self, path: Path) -> NoOpContentStore: # ruff:ignore[unused-method-argument, no-self-use] protocol diff --git a/tests/python_discovery/test_cache.py b/tests/python_discovery/test_cache.py index 1fd5abe..57a0aed 100644 --- a/tests/python_discovery/test_cache.py +++ b/tests/python_discovery/test_cache.py @@ -120,6 +120,36 @@ def test_disk_content_store_lock_permissions( ) == (lock_folder_mode, lock_mode) +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX ownership and modes") +@pytest.mark.parametrize( + ("owner_offset", "mode"), + [pytest.param(1, 0o700, id="foreign-owner"), pytest.param(0, 0o770, id="group-writable")], +) +def test_disk_content_store_rejects_untrusted_lock_folder( + tmp_path: Path, mocker: MockerFixture, owner_offset: int, mode: int +) -> None: + (lock_folder := tmp_path / "locks-v2").mkdir() + lock_folder.chmod(mode) + status = list(lock_folder.stat()) + status[4] = os.geteuid() + owner_offset + mocker.patch.object(Path, "lstat", return_value=os.stat_result(status), autospec=True) + with pytest.raises(PermissionError, match="untrusted lock directory"), DiskContentStore(tmp_path, "test").locked(): + pass # pragma: no cover, the lock folder is rejected first + assert not list(lock_folder.iterdir()) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX symbolic links") +@pytest.mark.parametrize("folder_mode", [pytest.param(0o755, id="private"), pytest.param(0o770, id="group-shared")]) +def test_disk_content_store_does_not_follow_lock_folder_link(tmp_path: Path, folder_mode: int) -> None: + (folder := tmp_path / "cache").mkdir() + folder.chmod(folder_mode) + (target := tmp_path / "target").mkdir() + (folder / "locks-v2").symlink_to(target, target_is_directory=True) + with pytest.raises(PermissionError, match="untrusted lock directory"), DiskContentStore(folder, "test").locked(): + pass # pragma: no cover, the lock folder is rejected first + assert not list(target.iterdir()) + + @pytest.mark.skipif(sys.platform == "win32", reason="POSIX lock migration") def test_disk_content_store_ignores_legacy_lock(tmp_path: Path) -> None: entered = Event() diff --git a/tests/python_discovery/test_cached_py_info.py b/tests/python_discovery/test_cached_py_info.py index c0e120c..af394d1 100644 --- a/tests/python_discovery/test_cached_py_info.py +++ b/tests/python_discovery/test_cached_py_info.py @@ -551,6 +551,20 @@ def test_from_exe_recovers_unusable_cache_path(tmp_path: Path, folder: str, suff assert result.version_info == expected.version_info +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX symbolic links") +def test_from_exe_does_not_lock_through_linked_folder(tmp_path: Path) -> None: + (target := tmp_path / "target").mkdir() + (folder := tmp_path / "cache" / "py_info" / "4").mkdir(parents=True) + (folder / "locks-v2").symlink_to(target, target_is_directory=True) + + result = PythonInfo.from_exe( + sys.executable, DiskCache(tmp_path / "cache"), ignore_cache=True, resolve_to_host=False + ) + + assert result is not None + assert not list(target.iterdir()) + + _LAUNCHER: Final[str] = r"C:\Program Files\Python Launcher\py.exe" _ARGS: Final[str] = '-3.11 --config "settings folder\\python.json"' _SELECTED: Final[str] = r"C:\Python311\python.exe" From d7add0e7662112c52bb9cc9ee3d7471a44a1146d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Sun, 29 Nov 2026 15:22:17 -0800 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9D=20docs(cache):=20drop=20unreac?= =?UTF-8?q?hable=20group=20clause?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DiskCache refuses a group-writable cache directory, so the lock rule in the explanation page only needs the private case. --- docs/explanation.rst | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/explanation.rst b/docs/explanation.rst index 4e4a9ed..868a951 100644 --- a/docs/explanation.rst +++ b/docs/explanation.rst @@ -296,10 +296,9 @@ private directory for the cache root, including when callers share a machine. A relative cache root refers to the current directory when ``DiskCache`` is created. On POSIX, lock files live in a ``locks-v2`` directory under the checked cache directory. Discovery uses it only when it -is a real directory that is owned by the current user or root and not writable by others, unless the cache directory is -group-writable; otherwise it logs a warning and queries the interpreter without the cache. Older releases use the -previous lock files, so processes running different releases do not coordinate cache writes. Use separate cache roots -while both run. +is a real directory that is owned by the current user or root and not writable by others; otherwise it logs a warning +and queries the interpreter without the cache. Older releases use the previous lock files, so processes running +different releases do not coordinate cache writes. Use separate cache roots while both run. Subprocess timeout behavior ----------------------------