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/+host-file-system-encoding.security.rst
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 4 additions & 2 deletions src/python_discovery/_cached_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:])}"
Expand Down
33 changes: 32 additions & 1 deletion src/python_discovery/_py_info_collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
41 changes: 40 additions & 1 deletion tests/python_discovery/test_cached_py_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
30 changes: 30 additions & 0 deletions tests/test_py_info_collect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down