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
7 changes: 7 additions & 0 deletions python/packages/tools/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
46 changes: 37 additions & 9 deletions python/packages/tools/agent_framework_tools/shell/_docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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":
Expand All @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
11 changes: 9 additions & 2 deletions python/packages/tools/agent_framework_tools/shell/_killtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
80 changes: 79 additions & 1 deletion python/packages/tools/agent_framework_tools/shell/_resolve.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from __future__ import annotations

import ntpath
import os
import shutil
import sys
Expand All @@ -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 ("\\", "/")
Comment thread
eavanvalkenburg marked this conversation as resolved.
Resolved


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.

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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}."
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`` —
Expand Down
1 change: 0 additions & 1 deletion python/packages/tools/tests/__init__.py

This file was deleted.

34 changes: 34 additions & 0 deletions python/packages/tools/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading