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
3 changes: 3 additions & 0 deletions docs/changelog/285.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 4 additions & 3 deletions docs/explanation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -295,9 +295,10 @@ 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; 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
----------------------------
Expand Down
22 changes: 16 additions & 6 deletions src/python_discovery/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -248,13 +244,27 @@ 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"))
with lock:
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
Expand Down
30 changes: 30 additions & 0 deletions tests/python_discovery/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
14 changes: 14 additions & 0 deletions tests/python_discovery/test_cached_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down