diff --git a/docs/changelog/+relative-spec-skip-path.security.rst b/docs/changelog/+relative-spec-skip-path.security.rst new file mode 100644 index 0000000..f406090 --- /dev/null +++ b/docs/changelog/+relative-spec-skip-path.security.rst @@ -0,0 +1,2 @@ +A relative path spec such as ``../venv/bin/python`` is no longer joined to ``PATH`` entries or searched for among +uv-managed installs, so its ``..`` segments can no longer run a file outside ``PATH``. diff --git a/src/python_discovery/_discovery.py b/src/python_discovery/_discovery.py index 00a70c2..84b1f2d 100644 --- a/src/python_discovery/_discovery.py +++ b/src/python_discovery/_discovery.py @@ -109,7 +109,7 @@ def propose_interpreters( return yield from _propose_explicit(spec, try_first_with, cache, env, tested_exes) - if spec.path is not None and spec.is_abs: # pragma: no cover # relative spec.path is never abs + if spec.path is not None and os.path.dirname(spec.path): # a ".." joined to a PATH entry escapes it return yield from _propose_from_path(spec, cache, env, tested_exes, all_implementations=all_implementations) yield from _propose_from_uv(spec, cache, env, all_implementations=all_implementations) diff --git a/tests/python_discovery/test_discovery.py b/tests/python_discovery/test_discovery.py index a6f6885..3aec8fd 100644 --- a/tests/python_discovery/test_discovery.py +++ b/tests/python_discovery/test_discovery.py @@ -239,6 +239,38 @@ def test_relative_path_with_parent_reference( assert Path(result.executable).samefile(sys_executable) +@pytest.mark.parametrize( + ("planted", "expected"), + [ + pytest.param([], set(), id="missing"), + pytest.param([Path("repo", "venv", _VENV_PYTHON)], {Path("repo", "venv", _VENV_PYTHON)}, id="present"), + ], +) +def test_relative_path_searches_only_working_directory( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + planted: list[Path], + expected: set[Path], +) -> None: + for relative in ( + *planted, + Path("tools", "venv", _VENV_PYTHON), + Path("tools", _SCRIPTS_DIR, _PYTHON_NAME), + Path("uv", "some-py-impl", _SCRIPTS_DIR, _PYTHON_NAME), + ): + (exe := tmp_path / relative).parent.mkdir(parents=True, exist_ok=True) + exe.touch(mode=0o755) + (tmp_path / "repo" / "package").mkdir(parents=True) + monkeypatch.chdir(tmp_path / "repo" / "package") + from_exe = mocker.patch("python_discovery._discovery.PythonInfo.from_exe", return_value=None, autospec=True) + env = {"PATH": str(tmp_path / "tools" / _SCRIPTS_DIR), "UV_PYTHON_INSTALL_DIR": str(tmp_path / "uv")} + spec = str(Path(os.pardir, "venv", _VENV_PYTHON)) + + assert (get_interpreter(spec, [], env=env), list(iter_interpreters(spec, [], env=env))) == (None, []) + assert {Path(call.args[0]).relative_to(tmp_path) for call in from_exe.call_args_list} == expected + + def test_discovery_fallback_fail(session_cache: DiskCache, caplog: pytest.LogCaptureFixture) -> None: caplog.set_level(logging.DEBUG) result = get_interpreter(["magic-one", "magic-two"], cache=session_cache)