From 4ceb78ca142a8e77e163642a3f02c1f84d6621ba Mon Sep 17 00:00:00 2001 From: Yin Date: Tue, 3 Nov 2026 02:08:28 +0800 Subject: [PATCH] fix(cli-apps): resolve Windows Python venv executables --- deeptutor/services/cli_apps/installer.py | 3 +- deeptutor/services/cli_apps/paths.py | 44 ++++- .../cli_apps/test_python_platform_install.py | 171 ++++++++++++++++++ .../cli_apps/test_python_platform_paths.py | 126 +++++++++++++ 4 files changed, 338 insertions(+), 6 deletions(-) create mode 100644 tests/services/cli_apps/test_python_platform_install.py create mode 100644 tests/services/cli_apps/test_python_platform_paths.py diff --git a/deeptutor/services/cli_apps/installer.py b/deeptutor/services/cli_apps/installer.py index 92d60a998..c3aeab13b 100644 --- a/deeptutor/services/cli_apps/installer.py +++ b/deeptutor/services/cli_apps/installer.py @@ -44,6 +44,7 @@ from deeptutor.services.cli_apps.paths import ( ensure_root, executable_path, install_log_path, + interpreter_path, runtime_dir, ) from deeptutor.services.cli_apps.state import ( @@ -206,7 +207,7 @@ def _steps(entry: CliAppEntry, env_dir) -> list[tuple[list[str], dict[str, str]] ([sys.executable, "-m", "venv", str(env_dir)], base), ( [ - str(env_dir / "bin" / "python"), + str(interpreter_path(env_dir)), "-m", "pip", "install", diff --git a/deeptutor/services/cli_apps/paths.py b/deeptutor/services/cli_apps/paths.py index cd9deee0b..82422dc2a 100644 --- a/deeptutor/services/cli_apps/paths.py +++ b/deeptutor/services/cli_apps/paths.py @@ -21,7 +21,8 @@ The layout under it:: data/cli-apps/ state.json # which apps are installed (deployment) apps// - venv/bin/ # a python app, one venv each + venv/bin/ # a python app, one venv each (Windows + # venvs: Scripts/.exe) node/bin/ # a node app, one prefix each install.log # last install's output, for the admin @@ -68,20 +69,52 @@ def runtime_dir(app_id: str, runtime: AppRuntime) -> Path: return app_dir(app_id) / "venv" +def _env_bin_dir(env_dir: Path, runtime: AppRuntime) -> Path: + """Where an environment's executables live. + + Only a Windows Python venv keeps them in ``Scripts``; a POSIX venv uses + ``bin``. Node environments also resolve to ``bin`` on every platform — + that is this app's own chosen, unchanged prefix layout for them, not a + claim about where npm natively installs executables on any given OS. + """ + if runtime is AppRuntime.PYTHON and os.name == "nt": + return env_dir / "Scripts" + return env_dir / "bin" + + def bin_dir(app_id: str, runtime: AppRuntime) -> Path: - return runtime_dir(app_id, runtime) / "bin" + return _env_bin_dir(runtime_dir(app_id, runtime), runtime) + + +def interpreter_path(env_dir: Path) -> Path: + """The Python interpreter of a venv rooted at *env_dir*. + + The caller supplies the environment directory — the installer drives one + it has not recorded in state yet — and the directory choice is shared + with :func:`bin_dir`, so the interpreter pip runs under and the entry + points it installs can never disagree. + """ + exe = "python.exe" if os.name == "nt" else "python" + return _env_bin_dir(env_dir, AppRuntime.PYTHON) / exe def executable_path(app_id: str, runtime: AppRuntime, entry_point: str) -> Path: """Absolute path of *entry_point* inside this app's own bin directory. ``entry_point`` comes from the catalog, so it is re-validated here rather - than only where the entry was parsed: this function is what turns it into a - path, and a separator or a ``..`` would name a file outside the app. + than only where the entry was parsed: this function is what turns it into + a path, and a separator or a ``..`` would name a file outside the app. + + The entry is a logical console-script name, not a caller-provided path: + on a Windows Python venv the on-disk name is it plus ``.exe``, appended + here after validation. """ if ENTRY_POINT_RE.match(entry_point) is None: raise ValueError(f"Unusable CLI app entry point {entry_point!r}") - return bin_dir(app_id, runtime) / entry_point + name = entry_point + if runtime is AppRuntime.PYTHON and os.name == "nt": + name = f"{entry_point}.exe" + return bin_dir(app_id, runtime) / name def install_log_path(app_id: str) -> Path: @@ -126,6 +159,7 @@ __all__ = [ "ensure_root", "executable_path", "install_log_path", + "interpreter_path", "runtime_dir", "state_path", ] diff --git a/tests/services/cli_apps/test_python_platform_install.py b/tests/services/cli_apps/test_python_platform_install.py new file mode 100644 index 000000000..612eb8230 --- /dev/null +++ b/tests/services/cli_apps/test_python_platform_install.py @@ -0,0 +1,171 @@ +"""Platform-dependent venv layout (Windows vs POSIX) for pip installs. + +The subprocess is fully faked: the venv "command" creates a plain interpreter +file, the pip "command" must address that exact interpreter and writes the +console script the layout demands. Only ``paths.os`` is patched — ``name`` +drives the layout, ``chmod`` stays real. Expected paths are built by hand so +a bug in a production layout helper cannot hide behind this test. +""" + +from __future__ import annotations + +import asyncio +import os +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from deeptutor.services.cli_apps import installer +from deeptutor.services.cli_apps import paths as cli_paths +from deeptutor.services.cli_apps import runner as cli_runner +from deeptutor.services.cli_apps.models import CliAppEntry, InstallKind +from deeptutor.services.cli_apps.state import load_installed +from deeptutor.services.sandbox.spec import ExecResult, Mount +from tests.services.cli_apps.test_installer import _entry + +_SECRET_MARKERS = ("KEY", "TOKEN", "SECRET", "PASSWORD") + + +class _FakeRunner: + """Stands in for ``installer._run``; no command is ever executed.""" + + def __init__(self, interpreter: Path, console: Path) -> None: + self.interpreter = interpreter + self.console = console + self.calls: list[tuple[list[str], dict[str, str]]] = [] + self.pip_code = 0 + self.pip_console: bytes | None = b"#!/bin/sh\n" + + def __call__(self, argv: list[str], *, env: dict[str, str]) -> tuple[int, str]: + self.calls.append((list(argv), dict(env))) + if "venv" in argv: + self.interpreter.parent.mkdir(parents=True, exist_ok=True) + self.interpreter.write_text("", encoding="utf-8") + return 0, "ok" + assert argv[0] == str(self.interpreter), argv + if "pip" in argv: + if self.pip_console is not None: + self.console.parent.mkdir(parents=True, exist_ok=True) + self.console.write_bytes(self.pip_console) + return self.pip_code, "boom" if self.pip_code else "ok" + raise AssertionError(f"unexpected command handed to the fake runner: {argv}") + + +def _layout( + name: str, cli_app_roots: Path, monkeypatch: pytest.MonkeyPatch +) -> tuple[Path, Path, Path]: + monkeypatch.setattr(cli_paths, "os", SimpleNamespace(name=name, chmod=os.chmod)) + envdir = Path(cli_app_roots) / "cli-apps" / "apps" / "demo" / "venv" + if name == "nt": + return ( + envdir, + envdir / "Scripts" / "python.exe", + envdir / "Scripts" / "cli-anything-demo.exe", + ) + return envdir, envdir / "bin" / "python", envdir / "bin" / "cli-anything-demo" + + +def _pip_entry() -> CliAppEntry: + return _entry(kind=InstallKind.PIP, target="demo-package") + + +@pytest.mark.parametrize("name", ["nt", "posix"]) +def test_successful_install_records_state_for_the_platform_layout( + name: str, cli_app_roots: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _envdir, interpreter, console = _layout(name, cli_app_roots, monkeypatch) + runner = _FakeRunner(interpreter, console) + monkeypatch.setattr(installer, "_run", runner) + monkeypatch.setenv("OPENAI_API_KEY", "fixture-secret-value") + + outcome = asyncio.run(installer.install_app(_pip_entry())) + + assert outcome.ok + assert console.read_bytes() == b"#!/bin/sh\n" + assert "demo" in load_installed() + for _argv, env in runner.calls: + assert not [key for key in env if any(m in key for m in _SECRET_MARKERS)] + assert "OPENAI_API_KEY" not in env + assert "fixture-secret-value" not in "".join(env.values()) + + +@pytest.mark.parametrize("name", ["nt", "posix"]) +def test_exit_zero_without_console_script_is_a_failed_install( + name: str, cli_app_roots: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _envdir, interpreter, console = _layout(name, cli_app_roots, monkeypatch) + runner = _FakeRunner(interpreter, console) + runner.pip_console = None + monkeypatch.setattr(installer, "_run", runner) + + outcome = asyncio.run(installer.install_app(_pip_entry())) + + assert not outcome.ok + assert not console.exists() + assert not load_installed() + + +@pytest.mark.parametrize("name", ["nt", "posix"]) +def test_failed_update_restores_the_previous_install( + name: str, cli_app_roots: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + envdir, interpreter, console = _layout(name, cli_app_roots, monkeypatch) + runner = _FakeRunner(interpreter, console) + monkeypatch.setattr(installer, "_run", runner) + entry = _pip_entry() + + first = asyncio.run(installer.install_app(entry)) + assert first.ok + old_console = console.read_bytes() + old_state = load_installed() + assert "demo" in old_state + + runner.pip_code = 1 + runner.pip_console = b"partial write" + outcome = asyncio.run(installer.install_app(entry)) + + assert not outcome.ok + assert console.read_bytes() == old_console + assert load_installed() == old_state + assert not (envdir.parent / "venv.old").exists() + + +@pytest.mark.parametrize("name", ["nt", "posix"]) +def test_run_app_sends_a_literal_argv_and_no_host_secrets( + name: str, cli_app_roots: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + envdir, interpreter, console = _layout(name, cli_app_roots, monkeypatch) + fake_install = _FakeRunner(interpreter, console) + monkeypatch.setattr(installer, "_run", fake_install) + outcome = asyncio.run(installer.install_app(_pip_entry())) + assert outcome.ok + app = outcome.app + + fake_service = SimpleNamespace(run=AsyncMock(return_value=ExecResult(stdout="ok"))) + monkeypatch.setattr("deeptutor.services.sandbox.get_sandbox_service", lambda: fake_service) + pathsep = ";" if name == "nt" else ":" + host_path = "C:\\host\\bin" if name == "nt" else "/usr/host/bin" + monkeypatch.setattr( + cli_runner, + "os", + SimpleNamespace( + environ={"PATH": host_path, "OPENAI_API_KEY": "fixture-secret-value"}, + pathsep=pathsep, + ), + ) + + args = ["--name", "two words", "; echo no"] + result = asyncio.run(cli_runner.run_app(app, args, user_id="u_test")) + + assert result.stdout == "ok" + fake_service.run.assert_awaited_once() + assert fake_service.run.await_args.kwargs == {"user_id": "u_test"} + request = fake_service.run.await_args.args[0] + assert request.argv == (str(console), "--name", "two words", "; echo no") + assert request.argv[1:] == tuple(args) + assert request.env["PATH"].split(pathsep)[0] == str(console.parent) + assert Mount(host_path=str(envdir), sandbox_path=str(envdir)) in request.mounts + assert "OPENAI_API_KEY" not in request.env + assert "fixture-secret-value" not in "".join(request.env.values()) diff --git a/tests/services/cli_apps/test_python_platform_paths.py b/tests/services/cli_apps/test_python_platform_paths.py new file mode 100644 index 000000000..5830aa189 --- /dev/null +++ b/tests/services/cli_apps/test_python_platform_paths.py @@ -0,0 +1,126 @@ +"""How the CLI app tree follows the host OS — and where it deliberately does not. + +A venv's executables live where the interpreter that built it puts them: +``Scripts`` with ``.exe`` console scripts on Windows, ``bin`` with +extension-less scripts elsewhere. A node prefix is the deployment's own +layout, so it keeps ``node/bin`` on every host. These tests pin that matrix +with a module-local OS proxy — the global ``os.name`` is never swapped, +because every other module in the process reads it too. +""" + +from __future__ import annotations + +import os +from pathlib import PurePosixPath, PureWindowsPath +import sys +from types import SimpleNamespace + +import pytest + +from deeptutor.services.cli_apps.installer import _steps +from deeptutor.services.cli_apps.models import ( + AppRuntime, + AppTrust, + CliAppEntry, + InstallKind, + InstallPlan, +) +from deeptutor.services.cli_apps.paths import bin_dir, executable_path + +_TARGET = "some-package" + +_ROOT = { + "nt": PureWindowsPath("C:/dt/cli-apps"), + "posix": PurePosixPath("/dt/cli-apps"), +} +#: Where a venv keeps its executables, per host. +_VENV_BIN = {"nt": "Scripts", "posix": "bin"} +#: The interpreter an installed venv is driven through, per host. +_VENV_PYTHON = {"nt": "python.exe", "posix": "python"} +#: What a console script's file name ends in, per host. +_SUFFIX = {"nt": ".exe", "posix": ""} + + +@pytest.fixture(params=("nt", "posix")) +def host(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> str: + """Run ``paths`` as if the process sat on one host OS at a time. + + The proxy replaces only what ``paths`` itself reads; the real ``os`` + module — and every other module importing it — keeps seeing the true + platform. + """ + from deeptutor.services.cli_apps import paths + + name = request.param + monkeypatch.setattr(paths, "os", SimpleNamespace(name=name, chmod=os.chmod)) + monkeypatch.setattr(paths, "cli_apps_root", lambda: _ROOT[name]) + return name + + +def _python_entry() -> CliAppEntry: + return CliAppEntry( + id="demo", + display_name="Demo", + description="A demo app", + category="utility", + origin="harness", + entry_point="demo", + install=InstallPlan( + kind=InstallKind.PIP, + runtime=AppRuntime.PYTHON, + trust=AppTrust.THIRD_PARTY, + target=_TARGET, + ), + ) + + +# ── the python layout ───────────────────────────────────────────────────── + + +def test_a_venvs_bin_directory_follows_the_host(host: str) -> None: + assert bin_dir("demo", AppRuntime.PYTHON) == ( + _ROOT[host] / "apps" / "demo" / "venv" / _VENV_BIN[host] + ) + + +def test_a_python_entry_point_gains_an_exe_only_on_windows(host: str) -> None: + assert executable_path("demo", AppRuntime.PYTHON, "demo") == ( + _ROOT[host] / "apps" / "demo" / "venv" / _VENV_BIN[host] / f"demo{_SUFFIX[host]}" + ) + + +# ── the node layout ─────────────────────────────────────────────────────── + + +def test_a_node_app_keeps_the_same_bin_layout_on_every_host(host: str) -> None: + """The prefix is the deployment's own layout, not the interpreter's.""" + assert executable_path("demo", AppRuntime.NODE, "demo") == ( + _ROOT[host] / "apps" / "demo" / "node" / "bin" / "demo" + ) + + +# ── entry-point validation ──────────────────────────────────────────────── + + +@pytest.mark.parametrize("entry_point", ["../bad", "a/b", "a\\b", "", "."]) +def test_an_unsafe_entry_point_is_refused_before_any_suffix(host: str, entry_point: str) -> None: + """``a\\b`` must not survive on nt by growing into ``Scripts\\a\\b.exe``.""" + with pytest.raises(ValueError, match="entry point"): + executable_path("demo", AppRuntime.PYTHON, entry_point) + + +# ── the install argv ────────────────────────────────────────────────────── + + +def test_pip_is_driven_through_the_venvs_own_python_for_the_host(host: str) -> None: + """``_steps`` only assembles argv — calling it runs nothing.""" + env_dir = _ROOT[host] / "apps" / "demo" / "venv" + steps = _steps(_python_entry(), env_dir) + + create, _ = steps[0] + assert create == [sys.executable, "-m", "venv", str(env_dir)] + + pip, _ = steps[1] + assert pip[0] == str(env_dir / _VENV_BIN[host] / _VENV_PYTHON[host]) + assert pip[1:3] == ["-m", "pip"] + assert pip[-1] == _TARGET