diff --git a/docs/changelog/+case-probe-private-dir.security.rst b/docs/changelog/+case-probe-private-dir.security.rst new file mode 100644 index 0000000..35f187e --- /dev/null +++ b/docs/changelog/+case-probe-private-dir.security.rst @@ -0,0 +1,2 @@ +Discovery no longer fails with :exc:`PermissionError`, or misdetects file-system case sensitivity, when the shared +temporary directory contains entries created by another user. diff --git a/src/python_discovery/_compat.py b/src/python_discovery/_compat.py index f9764df..bd28594 100644 --- a/src/python_discovery/_compat.py +++ b/src/python_discovery/_compat.py @@ -23,8 +23,11 @@ def fs_path_id(path: str) -> str: @functools.lru_cache(maxsize=1) def fs_is_case_sensitive() -> bool: - with tempfile.NamedTemporaryFile(prefix="TmP") as tmp_file: - result = not pathlib.Path(tmp_file.name.lower()).exists() + # Probe in a private directory: the shared temp dir may hold another user's lower-cased twin of the name. + with tempfile.TemporaryDirectory() as folder: + probe = pathlib.Path(folder, "TmP") + probe.touch() + result = not probe.with_name(probe.name.lower()).exists() _LOGGER.debug("filesystem is %scase-sensitive", "" if result else "not ") return result diff --git a/tests/python_discovery/test_compat.py b/tests/python_discovery/test_compat.py new file mode 100644 index 0000000..f75d8cc --- /dev/null +++ b/tests/python_discovery/test_compat.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import tempfile +from typing import TYPE_CHECKING + +import pytest + +from python_discovery._compat import fs_is_case_sensitive + +if TYPE_CHECKING: + from collections.abc import Generator + from pathlib import Path + + from pytest_mock import MockerFixture + + +@pytest.fixture +def _fresh_case_sensitivity_probe() -> Generator[None]: + fs_is_case_sensitive.cache_clear() + yield + fs_is_case_sensitive.cache_clear() + + +@pytest.mark.usefixtures("_fresh_case_sensitivity_probe") +def test_fs_is_case_sensitive_ignores_lower_cased_twin_in_shared_temp_dir( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture +) -> None: + (case_probe := tmp_path / "CaSe").touch() + expected = not case_probe.with_name("case").exists() + shared = tmp_path / "shared" + shared.mkdir() + (shared / "tmpabcdef").touch() + monkeypatch.setattr(tempfile, "tempdir", str(shared)) + mocker.patch("tempfile._get_candidate_names", autospec=True, return_value=iter(["AbCdEf", "GhIjKl"])) + + assert fs_is_case_sensitive() is expected