diff --git a/python/packages/tools/README.md b/python/packages/tools/README.md index 539e8dbb386..14585e8ca95 100644 --- a/python/packages/tools/README.md +++ b/python/packages/tools/README.md @@ -126,6 +126,13 @@ are not stopped solely because either output allowance is exceeded. - **Linux / macOS**: `/bin/bash --noprofile --norc` (falls back to `/bin/sh`). - Override via the `shell=` constructor argument or the `AGENT_FRAMEWORK_SHELL` environment variable. +- **Windows executable lookup**: a bare executable name (the default `pwsh` or + `powershell`, a bare `shell=` or `AGENT_FRAMEWORK_SHELL` value, and the + `docker_binary` of `DockerShellTool`) is looked up only in the fully + qualified entries of `PATH`. The current directory and relative `PATH` + entries are never searched. Pass an absolute path to select a specific + executable. A path, like a `PATH` match, shows only that the file exists, not + that it can be trusted, so keep `PATH` and the directories on it protected. ## `ShellEnvironmentProvider` — context provider diff --git a/python/packages/tools/agent_framework_tools/shell/_docker.py b/python/packages/tools/agent_framework_tools/shell/_docker.py index 3ef14e2f661..1fbe3609758 100644 --- a/python/packages/tools/agent_framework_tools/shell/_docker.py +++ b/python/packages/tools/agent_framework_tools/shell/_docker.py @@ -59,6 +59,7 @@ from .._feature_usage import FeatureIndex from ._capture import _ProcessOutput # pyright: ignore[reportPrivateUsage] - shared shell capture from ._policy import ShellPolicy, ShellRequest +from ._resolve import resolve_executable from ._session import ShellSession from ._truncate import _validate_output_limit # pyright: ignore[reportPrivateUsage] - shared limit validation from ._types import ( @@ -92,7 +93,15 @@ class DockerNotAvailableError(RuntimeError): def is_docker_available(binary: str = "docker") -> bool: - """Return ``True`` if ``binary`` is on PATH and the daemon responds.""" + """Return ``True`` if ``binary`` is on PATH and the daemon responds. + + On Windows, a bare ``binary`` is looked up only in the fully qualified entries of ``PATH``. The + current directory is never searched. + """ + try: + binary = resolve_executable(binary) + except FileNotFoundError: + return False if shutil.which(binary) is None: return False try: @@ -278,7 +287,11 @@ class DockerShellTool: with the default isolation flags and a trusted runtime — is the intended boundary rather than approval. on_command: Audit hook fired for every allowed command. - docker_binary: Override (e.g. ``"podman"``). + docker_binary: Override (e.g. ``"podman"``). On Windows, a bare name is + looked up only in the fully qualified entries of ``PATH``; the current + directory is never searched. Pass an absolute path to select a specific + executable. A path, like a ``PATH`` match, shows only that the file + exists, not that it can be trusted. shell: Shell binary to invoke inside the container. Defaults to ``"bash"``; pass ``"sh"`` for minimal images such as Alpine that don't ship bash. Anything else must be present on @@ -338,6 +351,7 @@ def __init__( self._binary = docker_binary self._shell = shell + self._resolved_binary: str | None = None self._session: ShellSession | None = None self._container_started = False self._lifecycle_lock: asyncio.Lock | None = None @@ -347,10 +361,24 @@ def _get_lifecycle_lock(self) -> asyncio.Lock: self._lifecycle_lock = asyncio.Lock() return self._lifecycle_lock + def _runtime_path(self) -> str: + """Return the container runtime to launch, resolved once for this instance. + + Resolving once keeps every launch of one instance on the same executable, so the runtime that + started a container is also the one that stops it. + """ + if self._resolved_binary is None: + self._resolved_binary = resolve_executable(self._binary) + return self._resolved_binary + # ------------------------------------------------------------------ lifecycle async def start(self) -> None: - """Pull/start the container and (if persistent) the inner shell session.""" + """Pull/start the container and (if persistent) the inner shell session. + + Raises: + FileNotFoundError: If the container runtime executable cannot be found. + """ # Stateless mode never uses the long-lived container — every call goes # through ``docker run --rm`` — so start()/close() are no-ops. if self._mode == "stateless": @@ -363,7 +391,7 @@ async def start(self) -> None: await self._start_container() self._container_started = True argv = build_exec_argv( - binary=self._binary, + binary=self._runtime_path(), container_name=self._container_name, interactive=True, shell=self._shell, # nosec B604 - 'shell' is the binary name kwarg, not subprocess shell=True @@ -439,7 +467,7 @@ async def _run_stateless(self, command: str, *, timeout: float | None) -> ShellR """Run a single command in a fresh ``docker run --rm`` container.""" per_call_name = f"af-shell-{secrets.token_hex(6)}" argv = [ - self._binary, + self._runtime_path(), "run", "--rm", "-i", @@ -510,7 +538,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str # Stopping the local client alone does not stop its container. try: killer = await asyncio.create_subprocess_exec( - self._binary, + self._runtime_path(), "kill", "--signal", "KILL", @@ -534,7 +562,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str if not kill_ok: logger.warning("docker kill of %s did not succeed; attempting docker rm -f", name) reaper = await asyncio.create_subprocess_exec( - self._binary, + self._runtime_path(), "rm", "-f", name, @@ -570,7 +598,7 @@ async def _terminate_stateless(self, proc: asyncio.subprocess.Process, name: str async def _start_container(self) -> None: argv = build_run_argv( - binary=self._binary, + binary=self._runtime_path(), image=self._image, container_name=self._container_name, user=self._user, @@ -606,7 +634,7 @@ async def _stop_container(self) -> None: async def _attempt(timeout: float) -> tuple[int | None, str]: """Run a single ``docker rm -f`` attempt. Returns (rc, stderr).""" proc = await asyncio.create_subprocess_exec( - self._binary, + self._runtime_path(), "rm", "-f", self._container_name, diff --git a/python/packages/tools/agent_framework_tools/shell/_killtree.py b/python/packages/tools/agent_framework_tools/shell/_killtree.py index ad3ae485fa1..bd8bcfb22b2 100644 --- a/python/packages/tools/agent_framework_tools/shell/_killtree.py +++ b/python/packages/tools/agent_framework_tools/shell/_killtree.py @@ -41,13 +41,20 @@ def _resolve_taskkill() -> str: - """Absolute path to taskkill.exe to defeat PATH poisoning.""" + """Absolute path to taskkill.exe to defeat PATH poisoning. + + Raises: + FileNotFoundError: If taskkill.exe is not in the system directory. The bare name is never used + as a fallback, because Windows would search the current directory for it first. + """ global _taskkill_path if _taskkill_path is not None: return _taskkill_path system_root = os.environ.get("SystemRoot") or os.environ.get("SYSTEMROOT") or r"C:\Windows" # ruff:ignore[uncapitalized-environment-variables] candidate = os.path.join(system_root, "System32", "taskkill.exe") - _taskkill_path = candidate if os.path.isfile(candidate) else "taskkill" + if not os.path.isfile(candidate): + raise FileNotFoundError(f"taskkill.exe was not found at {candidate}") + _taskkill_path = candidate return _taskkill_path diff --git a/python/packages/tools/agent_framework_tools/shell/_resolve.py b/python/packages/tools/agent_framework_tools/shell/_resolve.py index 724bbd98041..513f4b1f216 100644 --- a/python/packages/tools/agent_framework_tools/shell/_resolve.py +++ b/python/packages/tools/agent_framework_tools/shell/_resolve.py @@ -4,6 +4,7 @@ from __future__ import annotations +import ntpath import os import shutil import sys @@ -14,6 +15,77 @@ _ENV_OVERRIDE = "AGENT_FRAMEWORK_SHELL" +def _is_fully_qualified(path: str) -> bool: + """Return whether ``path`` names a fixed location that does not depend on the current directory.""" + drive, rest = ntpath.splitdrive(path) + if drive.replace("/", "\\").startswith("\\\\"): + # A UNC or device root such as \\server\share is complete without a trailing separator. + return True + return bool(drive) and rest[:1] in ("\\", "/") + + +def find_executable(name: str) -> str | None: + """Find a bare executable name in the fully qualified entries of ``PATH``. + + The search follows Windows naming rules and never uses the current directory. Windows starts a + bare name from the current directory of the host process before it reads ``PATH``, and + :func:`shutil.which` puts that directory first too, so a file in that directory could replace the + intended executable. Empty, relative, drive-relative, and drive-less rooted ``PATH`` entries + depend on the current directory, so they are skipped. + + Args: + name: A bare file name. ``.exe`` is added when it has no extension, as Windows does. + + Returns: + The absolute path of the first match, or ``None`` when no fully qualified ``PATH`` entry holds + the file. A match shows only that the file exists there, not who owns it or whether it can be + trusted. + """ + candidate = name if ntpath.splitext(name)[1] else f"{name}.exe" + # PATH entries are sometimes quoted; Windows tools differ in whether they strip the quotes. + for raw_entry in os.environ.get("PATH", "").split(ntpath.pathsep): + entry = raw_entry.strip().strip('"') + if not _is_fully_qualified(entry): + continue + path = ntpath.join(entry, candidate) + if os.path.isfile(path): + return path + return None + + +def resolve_executable(name: str) -> str: + """Return ``name`` in a form that can be launched without searching the current directory. + + On Windows a bare name is replaced by the path that :func:`find_executable` returns. Every other + value is returned unchanged: names with a directory or a drive are an explicit choice of the caller, + and other platforms do not search the current directory for bare names. + + Args: + name: The executable name or path that the caller configured. + + Raises: + FileNotFoundError: On Windows, when a bare name is not found in the fully qualified ``PATH`` + entries. The bare name is never used as a fallback. + """ + if sys.platform != "win32" or ntpath.dirname(name) or ntpath.splitdrive(name)[0]: + return name + found = find_executable(name) + if found is None: + raise FileNotFoundError( + f"Executable {name!r} was not found in the fully qualified entries of PATH. " + "The current directory and relative PATH entries are not searched." + ) + return found + + +def _qualify_shell(parts: list[str]) -> list[str]: + """Resolve the executable of an explicit shell override.""" + try: + return [resolve_executable(parts[0]), *parts[1:]] + except FileNotFoundError as exc: + raise ShellExecutionError(str(exc)) from exc + + def resolve_shell(shell: str | Sequence[str] | None, *, interactive: bool) -> list[str]: """Resolve the shell invocation argv. @@ -24,6 +96,10 @@ def resolve_shell(shell: str | Sequence[str] | None, *, interactive: bool) -> li 2. ``AGENT_FRAMEWORK_SHELL`` environment variable. 3. Platform default. + On Windows, a bare shell name (the default or an override) is resolved from the fully + qualified entries of ``PATH``; the current directory is never searched. Names that contain + a directory or a drive are used as given. + When ``interactive=False`` (stateless mode), the returned argv is guaranteed to end with a ``-c`` (POSIX) or ``-Command`` (PowerShell) flag so the caller can append a command string verbatim. Overrides @@ -48,6 +124,7 @@ def resolve_shell(shell: str | Sequence[str] | None, *, interactive: bool) -> li parts = list(shell) if not parts: raise ShellExecutionError("shell override must not be empty") + parts = _qualify_shell(parts) return parts if interactive else _ensure_command_flag(parts) env_override = os.environ.get(_ENV_OVERRIDE) @@ -56,10 +133,11 @@ def resolve_shell(shell: str | Sequence[str] | None, *, interactive: bool) -> li parts = shlex.split(env_override) if parts: + parts = _qualify_shell(parts) return parts if interactive else _ensure_command_flag(parts) if sys.platform == "win32": - binary = shutil.which("pwsh") or shutil.which("powershell") + binary = find_executable("pwsh") or find_executable("powershell") if binary is None: raise ShellExecutionError( f"Neither 'pwsh' nor 'powershell' was found on PATH. Install PowerShell 7+ or set {_ENV_OVERRIDE}." diff --git a/python/packages/tools/agent_framework_tools/shell/_tool.py b/python/packages/tools/agent_framework_tools/shell/_tool.py index a2ab434187d..85a61e7acb0 100644 --- a/python/packages/tools/agent_framework_tools/shell/_tool.py +++ b/python/packages/tools/agent_framework_tools/shell/_tool.py @@ -105,7 +105,11 @@ class LocalShellTool: shell: Optional shell argv override. String values are tokenised. When omitted, the platform default is used (``pwsh`` or ``powershell`` on Windows, ``bash`` or ``sh`` on Unix). May also - be overridden via the ``AGENT_FRAMEWORK_SHELL`` env var. + be overridden via the ``AGENT_FRAMEWORK_SHELL`` env var. On + Windows, a bare executable name (the default or an override) is + looked up only in the fully qualified entries of ``PATH``; the + current directory is never searched. Pass an absolute path to + select a specific executable. workdir: Working directory for commands. Defaults to the current working directory. In persistent mode, each command is re-anchored to this directory when ``confine_workdir=True`` — diff --git a/python/packages/tools/tests/__init__.py b/python/packages/tools/tests/__init__.py deleted file mode 100644 index 2a50eae8941..00000000000 --- a/python/packages/tools/tests/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Copyright (c) Microsoft. All rights reserved. diff --git a/python/packages/tools/tests/conftest.py b/python/packages/tools/tests/conftest.py new file mode 100644 index 00000000000..6636f73b5fb --- /dev/null +++ b/python/packages/tools/tests/conftest.py @@ -0,0 +1,34 @@ +# Copyright (c) Microsoft. All rights reserved. + +"""Shared fixtures for the shell tool tests.""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Callable, Iterable + +import pytest + + +@pytest.fixture +def fake_windows_host(monkeypatch: pytest.MonkeyPatch) -> Callable[[str, Iterable[str]], None]: + """Return a factory that makes the process look like a Windows host. + + Each call sets ``sys.platform`` and ``PATH``, and makes ``os.path.isfile`` report only the given files. A + later call replaces the files of an earlier call. The host file system is never consulted, so a real + installation directory cannot change the result. No file is created and no executable is started, so tests + that use it behave the same on every platform. + """ + + def configure(path_env: str, files: Iterable[str]) -> None: + known = frozenset(files) + + def isfile(candidate: str | os.PathLike[str]) -> bool: + return os.fspath(candidate) in known + + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.setenv("PATH", path_env) + monkeypatch.setattr(os.path, "isfile", isfile) + + return configure diff --git a/python/packages/tools/tests/test_docker_shell_tool.py b/python/packages/tools/tests/test_docker_shell_tool.py index f6f80c6854c..7b2bd52c273 100644 --- a/python/packages/tools/tests/test_docker_shell_tool.py +++ b/python/packages/tools/tests/test_docker_shell_tool.py @@ -14,12 +14,13 @@ import json import subprocess import sys -from collections.abc import Sequence -from typing import TypeAlias +from collections.abc import Callable, Iterable, Sequence +from typing import TypeAlias, cast from unittest.mock import AsyncMock, MagicMock, patch import pytest +import agent_framework_tools.shell._docker as docker_module from agent_framework_tools._feature_usage import FeatureIndex from agent_framework_tools.shell import ( DockerNotAvailableError, @@ -30,9 +31,27 @@ is_docker_available, ) from agent_framework_tools.shell._docker import build_exec_argv, build_run_argv +from agent_framework_tools.shell._resolve import resolve_executable _CommunicateOutcome: TypeAlias = tuple[bytes, bytes] | BaseException _WaitOutcome: TypeAlias = int | None | BaseException +_FakeWindowsHost: TypeAlias = Callable[[str, Iterable[str]], None] + +_RUNTIME_DIR = r"C:\Runtimes" +_DOCKER_EXE = rf"{_RUNTIME_DIR}\docker.exe" +_CREATE_PROCESS = "agent_framework_tools.shell._docker.asyncio.create_subprocess_exec" + + +@pytest.fixture(autouse=True) +def _pin_runtime_lookup(monkeypatch: pytest.MonkeyPatch) -> None: + """Keep the launch tests independent of the container runtimes installed on the host.""" + monkeypatch.setattr(docker_module, "resolve_executable", lambda name: name) + + +@pytest.fixture +def real_runtime_lookup(monkeypatch: pytest.MonkeyPatch) -> None: + """Use the real executable lookup for tests that check how the runtime is resolved.""" + monkeypatch.setattr(docker_module, "resolve_executable", resolve_executable) class _FakeProcess: @@ -718,6 +737,145 @@ async def test_as_function_surfaces_command_errors() -> None: assert "persistent session" in function.description +# --------------------------------------------------------------------- executable lookup + + +async def test_persistent_lifecycle_launches_only_the_qualified_runtime_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {_DOCKER_EXE, r".\docker.exe", "docker.exe"}) + tool = DockerShellTool() + started = _FakeProcess(returncode=0, communicate_results=[(b"abcdef123456\n", b"")]) + stopped = _FakeProcess(returncode=0, communicate_results=[(b"", b"")]) + + with ( + patch(_CREATE_PROCESS, AsyncMock(side_effect=[started, stopped])) as create_proc, + patch("agent_framework_tools.shell._docker.ShellSession", return_value=AsyncMock()) as shell_session, + ): + await tool.start() + await tool.close() + + assert [call.args[:2] for call in create_proc.await_args_list] == [(_DOCKER_EXE, "run"), (_DOCKER_EXE, "rm")] + assert shell_session.call_args.args[0][:2] == [_DOCKER_EXE, "exec"] + + +async def test_stateless_run_launches_the_qualified_runtime_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {_DOCKER_EXE, r".\docker.exe", "docker.exe"}) + tool = DockerShellTool(mode="stateless") + proc = _FakeProcess(returncode=0, communicate_results=[(b"", b"")]) + + with patch(_CREATE_PROCESS, AsyncMock(return_value=proc)) as create_proc: + await tool._run_stateless("echo hi", timeout=5.0) + + assert create_proc.await_args is not None + assert create_proc.await_args.args[:2] == (_DOCKER_EXE, "run") + + +async def test_stateless_cleanup_launches_the_qualified_runtime_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {_DOCKER_EXE, r".\docker.exe", "docker.exe"}) + tool = DockerShellTool(mode="stateless") + victim = _FakeProcess(returncode=None) + killer = _FakeProcess(returncode=1) + reaper = _FakeProcess(returncode=0) + + with patch(_CREATE_PROCESS, AsyncMock(side_effect=[killer, reaper])) as create_proc: + await tool._terminate_stateless(cast(asyncio.subprocess.Process, victim), "af-shell-test") + + assert [call.args[:2] for call in create_proc.await_args_list] == [(_DOCKER_EXE, "kill"), (_DOCKER_EXE, "rm")] + assert victim.killed + + +async def test_launch_is_refused_when_the_runtime_exists_only_in_the_current_directory_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {r".\docker.exe", "docker.exe"}) + persistent = DockerShellTool() + stateless = DockerShellTool(mode="stateless") + + with patch(_CREATE_PROCESS, AsyncMock()) as create_proc: + with pytest.raises(FileNotFoundError, match="'docker'"): + await persistent.start() + with pytest.raises(FileNotFoundError, match="'docker'"): + await stateless.run("echo hi") + + create_proc.assert_not_awaited() + + +async def test_container_is_stopped_with_the_runtime_that_started_it_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(_RUNTIME_DIR, {_DOCKER_EXE}) + tool = DockerShellTool() + started = _FakeProcess(returncode=0, communicate_results=[(b"abcdef123456\n", b"")]) + stopped = _FakeProcess(returncode=0, communicate_results=[(b"", b"")]) + + with ( + patch(_CREATE_PROCESS, AsyncMock(side_effect=[started, stopped])) as create_proc, + patch("agent_framework_tools.shell._docker.ShellSession", return_value=AsyncMock()), + ): + await tool.start() + fake_windows_host(r"C:\Other", {r"C:\Other\docker.exe"}) + await tool.close() + + assert [call.args[0] for call in create_proc.await_args_list] == [_DOCKER_EXE, _DOCKER_EXE] + + +async def test_explicit_runtime_path_is_launched_unchanged_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(_RUNTIME_DIR, {_DOCKER_EXE}) + tool = DockerShellTool(mode="stateless", docker_binary=r"C:\Custom\podman.exe") + proc = _FakeProcess(returncode=0, communicate_results=[(b"", b"")]) + + with patch(_CREATE_PROCESS, AsyncMock(return_value=proc)) as create_proc: + await tool._run_stateless("echo hi", timeout=5.0) + + assert create_proc.await_args is not None + assert create_proc.await_args.args[0] == r"C:\Custom\podman.exe" + + +async def test_run_stateless_uses_the_configured_binary_unchanged_on_other_platforms( + real_runtime_lookup: None, monkeypatch: pytest.MonkeyPatch +) -> None: + tool = DockerShellTool(mode="stateless", docker_binary="podman") + proc = _FakeProcess(returncode=0, communicate_results=[(b"", b"")]) + monkeypatch.setattr(sys, "platform", "linux") + + with patch(_CREATE_PROCESS, AsyncMock(return_value=proc)) as create_proc: + await tool._run_stateless("echo hi", timeout=5.0) + + assert create_proc.await_args is not None + assert create_proc.await_args.args[0] == "podman" + + +def test_is_docker_available_uses_the_qualified_runtime_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None, monkeypatch: pytest.MonkeyPatch +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {_DOCKER_EXE, r".\docker.exe", "docker.exe"}) + monkeypatch.setattr(docker_module.shutil, "which", lambda name: name) + completed = subprocess.CompletedProcess(args=[], returncode=0, stdout=b"27.0.1\n", stderr=b"") + + with patch("agent_framework_tools.shell._docker.subprocess.run", return_value=completed) as run: + assert is_docker_available() is True + + assert run.call_args.args[0][0] == _DOCKER_EXE + + +def test_is_docker_available_is_false_when_the_runtime_exists_only_in_the_current_directory_on_windows( + fake_windows_host: _FakeWindowsHost, real_runtime_lookup: None +) -> None: + fake_windows_host(f".;{_RUNTIME_DIR}", {r".\docker.exe", "docker.exe"}) + + with patch("agent_framework_tools.shell._docker.subprocess.run") as run: + assert is_docker_available() is False + + run.assert_not_called() + + # --------------------------------------------------------------------- integration diff --git a/python/packages/tools/tests/test_local_shell_tool.py b/python/packages/tools/tests/test_local_shell_tool.py index 83b6396d237..b7040f310cb 100644 --- a/python/packages/tools/tests/test_local_shell_tool.py +++ b/python/packages/tools/tests/test_local_shell_tool.py @@ -31,7 +31,7 @@ from agent_framework_tools.shell._truncate import _OutputBuffer from agent_framework_tools.shell._types import ShellMode -_TEST_SHELL = "agent-framework-test-shell" +_TEST_SHELL = "/opt/agent-framework-test-shell" _APPROVED_COMMAND = "printf '%s' approved-value" _ALTERNATE_COMMAND = "printf '%s' alternate-value" _POWERSHELL = shutil.which("pwsh") or (shutil.which("powershell") if sys.platform == "win32" else None) @@ -585,7 +585,7 @@ async def test_local_shell_tool_as_function_returns_policy_errors() -> None: def test_local_shell_tool_reanchors_powershell_paths() -> None: tool = LocalShellTool( mode="persistent", - shell="pwsh", + shell="/usr/bin/pwsh", workdir="C:\\repo", approval_mode="never_require", acknowledge_unsafe=True, diff --git a/python/packages/tools/tests/test_shell_killtree.py b/python/packages/tools/tests/test_shell_killtree.py index 011b9d8337b..bb7cc4bc5fb 100644 --- a/python/packages/tools/tests/test_shell_killtree.py +++ b/python/packages/tools/tests/test_shell_killtree.py @@ -5,6 +5,8 @@ from typing import Any, cast from unittest.mock import AsyncMock, MagicMock, patch +import pytest + from agent_framework_tools.shell._killtree import ( _kill_via_psutil, _kill_via_stdlib, @@ -58,6 +60,19 @@ def test_resolve_taskkill_uses_systemroot_and_caches(monkeypatch) -> None: assert _resolve_taskkill() == expected_path +def test_resolve_taskkill_refuses_the_bare_name_when_the_system_binary_is_missing(monkeypatch) -> None: + import agent_framework_tools.shell._killtree as killtree_module + + monkeypatch.setattr(killtree_module, "_taskkill_path", None) + monkeypatch.setenv("SystemRoot", "C:\\Windows") + monkeypatch.setattr(killtree_module.os.path, "isfile", lambda path: False) + + with pytest.raises(FileNotFoundError, match="taskkill.exe"): + _resolve_taskkill() + + assert killtree_module._taskkill_path is None + + async def test_kill_process_tree_short_circuits_or_delegates(monkeypatch) -> None: import agent_framework_tools.shell._killtree as killtree_module @@ -129,6 +144,23 @@ async def test_kill_via_stdlib_windows_uses_taskkill_and_proc_kill(monkeypatch) assert raw_proc.killed is True +async def test_kill_via_stdlib_windows_does_not_launch_taskkill_when_it_is_missing(monkeypatch) -> None: + import agent_framework_tools.shell._killtree as killtree_module + + monkeypatch.setattr(killtree_module.sys, "platform", "win32") + monkeypatch.setattr(killtree_module, "_taskkill_path", None) + monkeypatch.setenv("SystemRoot", "C:\\Windows") + monkeypatch.setattr(killtree_module.os.path, "isfile", lambda path: False) + raw_proc = _FakeAsyncProcess(pid=55, returncode=None) + proc = cast(asyncio.subprocess.Process, raw_proc) + + with patch("agent_framework_tools.shell._killtree.asyncio.create_subprocess_exec", AsyncMock()) as create_proc: + await _kill_via_stdlib(proc, grace=0.01) + + create_proc.assert_not_awaited() + assert raw_proc.killed is True + + async def test_kill_via_stdlib_posix_escalates_to_sigkill(monkeypatch) -> None: import agent_framework_tools.shell._killtree as killtree_module diff --git a/python/packages/tools/tests/test_shell_resolve.py b/python/packages/tools/tests/test_shell_resolve.py index 845a982e1bd..b8c727e49b3 100644 --- a/python/packages/tools/tests/test_shell_resolve.py +++ b/python/packages/tools/tests/test_shell_resolve.py @@ -1,9 +1,26 @@ # Copyright (c) Microsoft. All rights reserved. +import sys +from collections.abc import Callable, Iterable +from pathlib import Path +from typing import TypeAlias + import pytest from agent_framework_tools.shell import ShellExecutionError -from agent_framework_tools.shell._resolve import _ensure_command_flag, is_powershell, resolve_shell +from agent_framework_tools.shell._resolve import ( + _ensure_command_flag, + find_executable, + is_powershell, + resolve_executable, + resolve_shell, +) + +_FakeWindowsHost: TypeAlias = Callable[[str, Iterable[str]], None] + +_TRUSTED_BIN = r"C:\Trusted\bin" +_POWERSHELL_7 = r"C:\Program Files\PowerShell\7" +_WINDOWS_POWERSHELL = r"C:\Windows\System32\WindowsPowerShell\v1.0" def test_empty_string_shell_override_rejected() -> None: @@ -27,13 +44,13 @@ def test_resolve_shell_prefers_environment_override(monkeypatch: pytest.MonkeyPa assert resolve_shell(None, interactive=False) == ["/custom/pwsh", "-NoProfile", "-Command"] -def test_resolve_shell_windows_defaults_and_missing_binary(monkeypatch: pytest.MonkeyPatch) -> None: - import agent_framework_tools.shell._resolve as resolve_module - - monkeypatch.setattr(resolve_module.sys, "platform", "win32") - monkeypatch.setattr(resolve_module.shutil, "which", lambda name: "C:/pwsh.exe" if name == "pwsh" else None) +def test_resolve_shell_windows_defaults_and_missing_binary( + fake_windows_host: _FakeWindowsHost, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("AGENT_FRAMEWORK_SHELL", raising=False) + fake_windows_host(_POWERSHELL_7, {rf"{_POWERSHELL_7}\pwsh.exe"}) assert resolve_shell(None, interactive=True) == [ - "C:/pwsh.exe", + rf"{_POWERSHELL_7}\pwsh.exe", "-NoLogo", "-NoProfile", "-NonInteractive", @@ -41,11 +58,178 @@ def test_resolve_shell_windows_defaults_and_missing_binary(monkeypatch: pytest.M "-", ] - monkeypatch.setattr(resolve_module.shutil, "which", lambda name: None) + fake_windows_host(_POWERSHELL_7, set()) with pytest.raises(ShellExecutionError, match="Neither 'pwsh' nor 'powershell'"): resolve_shell(None, interactive=False) +def test_resolve_shell_windows_default_ignores_executables_in_the_current_directory( + fake_windows_host: _FakeWindowsHost, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("AGENT_FRAMEWORK_SHELL", raising=False) + fake_windows_host( + rf".;{_WINDOWS_POWERSHELL}", + {r".\pwsh.exe", r".\pwsh.cmd", r".\powershell.exe", rf"{_WINDOWS_POWERSHELL}\powershell.exe"}, + ) + + assert resolve_shell(None, interactive=False)[0] == rf"{_WINDOWS_POWERSHELL}\powershell.exe" + + fake_windows_host(rf".;{_TRUSTED_BIN}", {r".\pwsh.exe", r".\powershell.cmd"}) + with pytest.raises(ShellExecutionError, match="Neither 'pwsh' nor 'powershell'"): + resolve_shell(None, interactive=False) + + +def test_resolve_shell_windows_resolves_bare_overrides( + fake_windows_host: _FakeWindowsHost, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("AGENT_FRAMEWORK_SHELL", raising=False) + fake_windows_host(f"{_POWERSHELL_7};{_TRUSTED_BIN}", {rf"{_POWERSHELL_7}\pwsh.exe", rf"{_TRUSTED_BIN}\bash.exe"}) + + assert resolve_shell("pwsh -NoProfile", interactive=True) == [rf"{_POWERSHELL_7}\pwsh.exe", "-NoProfile"] + assert resolve_shell(["bash", "--norc"], interactive=True) == [rf"{_TRUSTED_BIN}\bash.exe", "--norc"] + monkeypatch.setenv("AGENT_FRAMEWORK_SHELL", "bash") + assert resolve_shell(None, interactive=False) == [rf"{_TRUSTED_BIN}\bash.exe", "-c"] + + +def test_resolve_shell_windows_rejects_a_bare_override_found_only_in_the_current_directory( + fake_windows_host: _FakeWindowsHost, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("AGENT_FRAMEWORK_SHELL", raising=False) + fake_windows_host(f".;{_TRUSTED_BIN}", {r".\bash.exe", "bash.exe"}) + + with pytest.raises(ShellExecutionError, match="'bash'"): + resolve_shell("bash", interactive=True) + monkeypatch.setenv("AGENT_FRAMEWORK_SHELL", "bash") + with pytest.raises(ShellExecutionError, match="'bash'"): + resolve_shell(None, interactive=True) + + +@pytest.mark.parametrize( + "shell", + [ + [rf"{_POWERSHELL_7}\pwsh.exe", "-NoProfile"], + [r".\pwsh.exe"], + ["/opt/pwsh"], + ], +) +def test_resolve_shell_windows_keeps_explicit_paths(fake_windows_host: _FakeWindowsHost, shell: list[str]) -> None: + fake_windows_host(_TRUSTED_BIN, set()) + + assert resolve_shell(shell, interactive=True) == shell + + +def test_find_executable_searches_only_fully_qualified_path_entries(fake_windows_host: _FakeWindowsHost) -> None: + fake_windows_host( + rf".;;bin;C:;C:Tools;\rooted;{_TRUSTED_BIN}", + { + r".\docker.exe", + r"bin\docker.exe", + r"C:docker.exe", + r"C:Tools\docker.exe", + r"\rooted\docker.exe", + rf"{_TRUSTED_BIN}\docker.exe", + }, + ) + + assert find_executable("docker") == rf"{_TRUSTED_BIN}\docker.exe" + + +def test_find_executable_returns_none_when_only_current_directory_dependent_entries_match( + fake_windows_host: _FakeWindowsHost, +) -> None: + fake_windows_host( + rf".;;bin;C:;C:Tools;\rooted;{_TRUSTED_BIN}", + { + r".\docker.exe", + "docker.exe", + r"bin\docker.exe", + "C:docker.exe", + r"C:Tools\docker.exe", + r"\rooted\docker.exe", + }, + ) + + assert find_executable("docker") is None + + +def test_find_executable_returns_the_first_match_in_path_order(fake_windows_host: _FakeWindowsHost) -> None: + fake_windows_host(r"C:\First;C:\Second", {r"C:\First\docker.exe", r"C:\Second\docker.exe"}) + + assert find_executable("docker") == r"C:\First\docker.exe" + + +@pytest.mark.parametrize( + ("name", "expected"), + [("pwsh", None), ("pwsh.exe", None), ("pwsh.cmd", rf"{_TRUSTED_BIN}\pwsh.cmd")], +) +def test_find_executable_adds_exe_only_to_names_without_an_extension( + fake_windows_host: _FakeWindowsHost, name: str, expected: str | None +) -> None: + fake_windows_host(_TRUSTED_BIN, {rf"{_TRUSTED_BIN}\pwsh.cmd"}) + + assert find_executable(name) == expected + + +def test_find_executable_accepts_quoted_and_unc_path_entries(fake_windows_host: _FakeWindowsHost) -> None: + fake_windows_host( + r'"C:\Program Files\Docker";\\server\share\bin', + {r"C:\Program Files\Docker\docker.exe", r"\\server\share\bin\podman.exe"}, + ) + + assert find_executable("docker") == r"C:\Program Files\Docker\docker.exe" + assert find_executable("podman") == r"\\server\share\bin\podman.exe" + + +@pytest.mark.parametrize( + ("entry", "expected"), + [ + (r"\\server\share", r"\\server\share\docker.exe"), + ("//server/share", r"//server/share\docker.exe"), + (r"\\?\UNC\server\share", r"\\?\UNC\server\share\docker.exe"), + ], +) +def test_find_executable_accepts_unc_share_roots_without_a_trailing_separator( + fake_windows_host: _FakeWindowsHost, entry: str, expected: str +) -> None: + fake_windows_host(entry, {expected}) + + assert find_executable("docker") == expected + + +@pytest.mark.parametrize( + "name", + [ + r"C:\tools\docker.exe", + r"\\server\share\docker.exe", + r".\docker.exe", + r"bin\docker.exe", + "C:docker.exe", + r"\docker.exe", + "/usr/bin/docker", + ], +) +def test_resolve_executable_returns_names_with_a_directory_or_drive_unchanged( + fake_windows_host: _FakeWindowsHost, name: str +) -> None: + fake_windows_host(_TRUSTED_BIN, set()) + + assert resolve_executable(name) == name + + +def test_resolve_executable_never_falls_back_to_the_bare_name_on_windows(fake_windows_host: _FakeWindowsHost) -> None: + fake_windows_host(f".;{_TRUSTED_BIN}", {r".\docker.exe", "docker.exe"}) + + with pytest.raises(FileNotFoundError, match="'docker'"): + resolve_executable("docker") + + +def test_resolve_executable_returns_names_unchanged_on_other_platforms(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setenv("PATH", "") + + assert resolve_executable("docker") == "docker" + + def test_resolve_shell_posix_fallbacks(monkeypatch: pytest.MonkeyPatch) -> None: import agent_framework_tools.shell._resolve as resolve_module @@ -84,7 +268,7 @@ def test_stateless_preserves_existing_dash_c_flag() -> None: def test_stateless_preserves_existing_pwsh_command_flag() -> None: - argv = resolve_shell("pwsh -NoProfile -Command", interactive=False) + argv = resolve_shell("/opt/pwsh -NoProfile -Command", interactive=False) assert argv[-1] == "-Command" # No second -Command appended. assert argv.count("-Command") == 1 @@ -93,3 +277,21 @@ def test_stateless_preserves_existing_pwsh_command_flag() -> None: def test_interactive_does_not_append_command_flag() -> None: argv = resolve_shell("/bin/bash --noprofile", interactive=True) assert "-c" not in argv + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows executable lookup") +def test_windows_lookup_ignores_executables_in_the_current_directory( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # The files are empty and never started: the lookup only inspects the file system. + for name in ("pwsh.exe", "pwsh.cmd", "powershell.exe", "powershell.cmd", "docker.exe"): + (tmp_path / name).write_text("") + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("AGENT_FRAMEWORK_SHELL", raising=False) + + shell = Path(resolve_shell(None, interactive=False)[0]) + runtime = find_executable("docker") + + assert shell.is_absolute() + assert shell.parent != tmp_path + assert runtime is None or Path(runtime).parent != tmp_path