From cd046e313c3aa813776811ed8db4db857d2fd71a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Sun, 29 Nov 2026 15:14:07 -0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(probe):=20report=20paths=20i?= =?UTF-8?q?n=20host=20file=20system=20encoding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The interrogation script runs in UTF-8 mode, but the host decodes the paths it gets back with its own file system encoding. Under a non-UTF-8 locale the same text named other bytes, so discovery could run a different file and return it as system_executable. The host now passes its file system encoding to the script, which re-encodes the reported paths into it. The cache entry records that encoding as well, so an entry written under one encoding is not read under another. Reported by oss-scanner as ANT-2026-794CGR4Y. --- .../+host-file-system-encoding.security.rst | 3 ++ src/python_discovery/_cached_py_info.py | 6 ++- src/python_discovery/_py_info_collect.py | 33 ++++++++++++++- tests/python_discovery/test_cached_py_info.py | 41 ++++++++++++++++++- tests/test_py_info_collect.py | 30 ++++++++++++++ 5 files changed, 109 insertions(+), 4 deletions(-) create mode 100644 docs/changelog/+host-file-system-encoding.security.rst diff --git a/docs/changelog/+host-file-system-encoding.security.rst b/docs/changelog/+host-file-system-encoding.security.rst new file mode 100644 index 0000000..13acf02 --- /dev/null +++ b/docs/changelog/+host-file-system-encoding.security.rst @@ -0,0 +1,3 @@ +Interpreter discovery under a non-UTF-8 locale could run and return a different file than the one requested. Reported +paths are now decoded with the file system encoding of the querying process, and cache entries are reused only under +the encoding they were written with. diff --git a/src/python_discovery/_cached_py_info.py b/src/python_discovery/_cached_py_info.py index 9070c89..d29dc43 100644 --- a/src/python_discovery/_cached_py_info.py +++ b/src/python_discovery/_cached_py_info.py @@ -54,11 +54,11 @@ from ._cache import ContentStore, PyInfoCache class CacheEntryMeta(TypedDict): - # Identity of a cached interrogation result: the queried binary, its arguments and the script. st_mtime: float path: str hash: str | None arguments: str | None + file_system_encoding: str _CACHE: Final[OrderedDict[tuple[Path, str | None], PythonInfo | Exception]] = OrderedDict() @@ -144,6 +144,7 @@ def _get_via_file_cache( # ruff:ignore[too-many-arguments] each argument is a s "path": path_text, "hash": py_info_hash, "arguments": executable_args, + "file_system_encoding": sys.getfilesystemencoding(), } with py_info_store.locked(): if (cached := _read_cache_entry(cls, py_info_store, entry_meta)) is not None: @@ -213,7 +214,8 @@ def _run_subprocess( end_cookie = gen_cookie() timeout = _query_timeout(env.get("PY_DISCOVERY_TIMEOUT")) with _resolve_py_info_script() as py_info_script: - cmd: list[str] | str = [exe, str(py_info_script), start_cookie, end_cookie] + # candidates run in UTF-8 mode, so they must be told how this process decodes file names + cmd: list[str] | str = [exe, str(py_info_script), start_cookie, end_cookie, sys.getfilesystemencoding()] if executable_args is not None: # PEP 514 ExecutableArguments is raw command line text, placed before the script per the PEP cmd = f"{list2cmdline(cmd[:1])} {executable_args} {list2cmdline(cmd[1:])}" diff --git a/src/python_discovery/_py_info_collect.py b/src/python_discovery/_py_info_collect.py index ed415a7..0d4a2fc 100644 --- a/src/python_discovery/_py_info_collect.py +++ b/src/python_discovery/_py_info_collect.py @@ -384,13 +384,44 @@ def _main(): # pragma: no cover # exercised via subprocess runs else: end_cookie = "" + if len(argv) >= 1: + file_system_encoding = argv[0] + argv = argv[1:] + else: + file_system_encoding = sys.getfilesystemencoding() + sys.argv = sys.argv[:1] + argv - result = json.dumps(PythonInfoCollector().to_dict(), indent=2) + # converted here so the host never looks up a codec the candidate names + result = json.dumps(_decoded_as(file_system_encoding, PythonInfoCollector().to_dict()), indent=2) sys.stdout.write("".join((start_cookie[::-1], result, end_cookie[::-1]))) sys.stdout.flush() +def _decoded_as(encoding, data): + own_encoding = sys.getfilesystemencoding() + if os.name == "nt" or encoding == own_encoding: # Windows file names are not bytes + return data + + def convert(value): + if not isinstance(value, str): + return value + try: + return value.encode(own_encoding, "surrogateescape").decode(encoding, "surrogateescape") + except UnicodeEncodeError: # not a file name, so there are no bytes to re-encode + return value + + result = {} + for key, value in data.items(): + if isinstance(value, list): + result[key] = [convert(item) for item in value] + elif isinstance(value, dict): + result[key] = {name: convert(item) for name, item in value.items()} + else: + result[key] = convert(value) + return result + + __all__ = [ "MIN_INTERROGATE_VERSION", "UNSUPPORTED_EXIT_CODE", diff --git a/tests/python_discovery/test_cached_py_info.py b/tests/python_discovery/test_cached_py_info.py index c0e120c..aeccf71 100644 --- a/tests/python_discovery/test_cached_py_info.py +++ b/tests/python_discovery/test_cached_py_info.py @@ -172,6 +172,26 @@ def test_run_subprocess_with_cookies(mocker: MockerFixture) -> None: assert mock_stdout.write.call_count == 2 +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell launcher, and Windows file names are not bytes") +def test_run_subprocess_names_files_as_host_does(tmp_path: Path) -> None: + directory = tmp_path / os.fsdecode(b"p\xc3\xa8re") + directory.mkdir() + python = directory / "python3" + python.symlink_to(sys.executable) + # Stands in for Python 3.6, which ignores PYTHONUTF8 and decodes file names as its locale says, here as ASCII. + launcher = directory / "python" + launcher.write_text( + '#!/bin/sh\nPYTHONUTF8=0 PYTHONCOERCECLOCALE=0 LC_ALL=C exec "$(dirname "$0")/python3" "$@"\n', encoding="utf-8" + ) + launcher.chmod(0o755) + + failure, result = _run_subprocess(PythonInfo, str(launcher), dict(os.environ)) + + assert failure is None + assert result is not None + assert result.original_executable == str(python) + + def test_run_subprocess_timeout(mocker: MockerFixture) -> None: mocker.patch( "python_discovery._cached_py_info._collect_query_output", return_value=("", "timed out", -1), autospec=True @@ -351,6 +371,25 @@ def test_get_via_file_cache_stale_hash(tmp_path: Path) -> None: assert isinstance(result2, PythonInfo) +def test_get_via_file_cache_other_file_system_encoding(tmp_path: Path, mocker: MockerFixture) -> None: + cache = DiskCache(tmp_path) + path = Path(sys.executable) + env = dict(os.environ) + assert isinstance(_get_via_file_cache(PythonInfo, cache, path, sys.executable, env), PythonInfo) + store = cache.py_info(path) + data = store.read() + assert data is not None + store.write({**data, "file_system_encoding": "another-encoding"}) + query = mocker.patch( + "python_discovery._cached_py_info._run_subprocess", return_value=(None, PythonInfo()), autospec=True + ) + + assert isinstance(_get_via_file_cache(PythonInfo, cache, path, sys.executable, env), PythonInfo) + + query.assert_called_once() + assert (store.read() or {}).get("file_system_encoding") == sys.getfilesystemencoding() + + def test_get_via_file_cache_nonexistent_path(tmp_path: Path) -> None: cache = DiskCache(tmp_path) path = Path(tmp_path / "nonexistent") @@ -571,7 +610,7 @@ def test_executable_args_precede_query_script(popen: MockType) -> None: cmd = popen.call_args.args[0] assert cmd.startswith(f"{list2cmdline([_LAUNCHER])} {_ARGS} ") - assert cmd.endswith(f" {'a' * 32} {'b' * 32}") + assert cmd.endswith(f" {'a' * 32} {'b' * 32} {sys.getfilesystemencoding()}") @pytest.mark.usefixtures("popen") diff --git a/tests/test_py_info_collect.py b/tests/test_py_info_collect.py index c9856fd..a4962e7 100644 --- a/tests/test_py_info_collect.py +++ b/tests/test_py_info_collect.py @@ -16,6 +16,7 @@ import python_discovery from python_discovery import PythonInfo +from python_discovery._py_info_collect import _decoded_as if TYPE_CHECKING: from collections.abc import Callable @@ -99,6 +100,35 @@ def test_script_payload_loads_as_python_info() -> None: assert info.executable == sys.executable +@pytest.mark.skipif(sys.platform == "win32", reason="Windows file names are not bytes") +def test_script_names_files_as_host_does(tmp_path: Path) -> None: + python = tmp_path / os.fsdecode(b"p\xc3\xa8re") / "python3" + python.parent.mkdir() + python.symlink_to(sys.executable) + env = {**os.environ, "PYTHONUTF8": "1"} + + out = run([str(python), str(_SCRIPT), "", "", "iso8859-1"], capture_output=True, text=True, check=True, env=env) + + assert json.loads(out.stdout)["executable"] == os.fsencode(python).decode("iso8859-1") + + +@pytest.mark.skipif(sys.platform == "win32", reason="Windows file names are not bytes") +def test_decoded_as_other_file_system_encoding() -> None: + name, lone_surrogate = os.fsdecode(b"/opt/p\xc3\xa8re"), "\ud800" + data = {"prefix": name, "path": [name, lone_surrogate], "sysconfig_vars": {"LIBDIR": name, "Py_DEBUG": 0}} + host_name = b"/opt/p\xc3\xa8re".decode("iso8859-1") + assert _decoded_as("iso8859-1", data) == { + "prefix": host_name, + "path": [host_name, lone_surrogate], + "sysconfig_vars": {"LIBDIR": host_name, "Py_DEBUG": 0}, + } + + +def test_decoded_as_own_file_system_encoding() -> None: + data = {"prefix": "/opt/python"} + assert _decoded_as(sys.getfilesystemencoding(), data) is data + + @pytest.fixture def no_framework(mocker: MockerFixture) -> None: get_config_var = sysconfig.get_config_var