From dba77b5e741d5c772ad5493ce45c7fc409416949 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sun, 6 Sep 2026 11:08:51 +0800 Subject: [PATCH] fix(cli): harden attach-only Desktop selection [skip ci] Preserve current Python startup when Desktop is not ready before target selection, while refusing fallback after the user chooses Desktop. Keep retained launchers and virtual environment labels consistent. Authenticate Windows pipe ownership before I/O and drain cancelled operations before releasing buffers. Add entrypoint, failure-path, transport and credential-safe browser regressions without changing backend lifecycle or configuration. --- docs/cli-reference.md | 10 +- nanobot/cli/commands.py | 17 ++ nanobot/cli/desktop_target.py | 186 +++++++++++++++---- nanobot/cli/entry.py | 2 +- tests/cli/test_desktop_target.py | 129 +++++++++++++ tests/cli/test_desktop_target_entrypoints.py | 62 +++++++ tests/cli/test_desktop_target_windows.py | 164 ++++++++++++++++ tests/cli/test_entry.py | 2 +- 8 files changed, 529 insertions(+), 43 deletions(-) create mode 100644 tests/cli/test_desktop_target_entrypoints.py create mode 100644 tests/cli/test_desktop_target_windows.py diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 5c3d2aac0..9c4e7fe03 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -38,15 +38,19 @@ python -m nanobot --version The Python package and Nanobot Desktop keep separate runtimes, configuration, workspaces, and state. When a running Desktop release publishes its private terminal-access descriptor, an interactive bare `nanobot` or `nanobot webui` -asks which installation to use for that invocation. With no running Desktop -target, the command reports the current Python executable and continues normally. +asks which installation to use after authenticating a ready Desktop target. +If Desktop is absent, busy, unavailable, or cannot be authenticated, the command +reports the current Python executable and continues normally. A virtual +environment's executable is shown without resolving it to its base interpreter. Choosing Desktop for `nanobot webui` opens its already-running browser workbench and exits; closing the browser never stops the Desktop gateway. The current -Desktop discovery protocol does not yet advertise attach-only terminal chat, so +Python client and Desktop discovery protocol do not yet support attach-only terminal chat, so choosing Desktop for bare `nanobot` fails explicitly without starting, restarting, or replacing a backend. Use explicit `nanobot agent` for the Python terminal UI until the Desktop TUI attachment protocol is available. +After Desktop is selected, a disconnect or incompatible reply ends that invocation +with an error; it never silently switches to Python or launches a replacement. Any explicit subcommand or option—including `nanobot agent`, `nanobot webui --no-open`, config/workspace selectors, help, version, completion, diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 2b64f3d11..cb655415f 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -23,6 +23,7 @@ if sys.platform == "win32": # Keep console encoding setup before importing CLI UI/logging libraries. import typer # noqa: E402 from loguru import logger # noqa: E402 +from typer.core import TyperGroup # noqa: E402 # Remove default handler and re-add with unified nanobot format logger.remove() @@ -83,7 +84,16 @@ from nanobot.utils.helpers import ( # noqa: E402 SafeFileHistory = cli_terminal.SafeFileHistory +class _DesktopAwareGroup(TyperGroup): + def parse_args(self, ctx: Any, args: list[str]) -> list[str]: + # Keep exact arguments: explicitly passing even a default-valued option + # must bypass the picker. Also covers older commands:app launchers. + ctx.meta["desktop_target_args"] = list(args) + return super().parse_args(ctx, args) + + app = typer.Typer( + cls=_DesktopAwareGroup, name="nanobot", context_settings={"help_option_names": ["-h", "--help"]}, help=f"{__logo__} nanobot - Personal AI Assistant", @@ -116,6 +126,13 @@ def main( # role identity correct until that launcher is regenerated. command = ctx.invoked_subcommand set_cli_process_identity([command] if command else ["agent"]) + from nanobot.cli.desktop_target import dispatch_bare_desktop_target + + raw_args = ctx.meta.get("desktop_target_args") + if isinstance(raw_args, list): + desktop_exit = dispatch_bare_desktop_target(cast(list[str], raw_args)) + if desktop_exit is not None: + raise typer.Exit(desktop_exit) if command is None: from nanobot.cli.entry import _run_agent diff --git a/nanobot/cli/desktop_target.py b/nanobot/cli/desktop_target.py index 9a46b5332..1b44c9bd9 100644 --- a/nanobot/cli/desktop_target.py +++ b/nanobot/cli/desktop_target.py @@ -11,6 +11,7 @@ import struct import sys import time import uuid +import webbrowser from dataclasses import dataclass from pathlib import Path from typing import Any, Literal, cast @@ -61,7 +62,7 @@ class DesktopTarget: return _parse_reply(raw, expected_instance_id=self.instance_id) except DesktopTargetError: raise - except Exception as exc: + except OSError as exc: raise DesktopTargetError("Desktop connection unavailable") from exc @@ -89,17 +90,19 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None: environment. An integer means the invocation was handled here and should exit with that status. """ - if args not in ([], ["webui"]) or not _interactive_shell(): + if ( + args not in ([], ["webui"]) + or os.environ.get("_NANOBOT_COMPLETE") + or not _interactive_shell() + ): return None try: target = discover_desktop_target() except DesktopTargetError: - _print_desktop_error( - "Nanobot Desktop discovery could not be authenticated. Restart Desktop, " - "or run `nanobot agent` to use this Python environment explicitly." - ) - return 3 + print("Nanobot Desktop discovery could not be authenticated.", file=sys.stderr) + _print_python_target() + return None if target is None: _print_python_target() @@ -108,12 +111,17 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None: try: status = target.request("status") except DesktopTargetError: - _print_desktop_error( - "Nanobot Desktop was discovered but did not accept an authenticated " - "connection. Restart Desktop, or run `nanobot agent` to use this Python " - "environment explicitly." - ) - return 3 + print("Nanobot Desktop is unavailable.", file=sys.stderr) + _print_python_target() + return None + + if status.state != "ready": + print(f"Nanobot Desktop is not ready ({status.state}).", file=sys.stderr) + _print_python_target() + return None + + if not args: + print("Desktop terminal chat attachment is not supported by this Python client yet.") if _choose_target(status) == "python": _print_python_target() @@ -131,7 +139,7 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None: _print_desktop_error(f"Nanobot Desktop is not ready ({current.state}).") return 3 _print_desktop_error( - "This Desktop version does not yet provide attach-only terminal chat. " + "This Python client does not yet provide attach-only terminal chat. " "Run `nanobot agent` to use this Python environment." ) return 4 @@ -139,12 +147,17 @@ def dispatch_bare_desktop_target(args: list[str]) -> int | None: try: reply = target.request("webui") url = _desktop_webui_url(reply) - from nanobot.cli.webui_support import _launch_browser - - opened = _launch_browser(url) except DesktopTargetError: _print_desktop_error("Nanobot Desktop disconnected or returned an incompatible WebUI.") return 3 + from nanobot.cli.webui_support import _launch_browser + + try: + opened = _launch_browser(url) + except (OSError, ValueError, webbrowser.Error): + # Browser exceptions can embed the credential-bearing URL. Report only + # the failure, never the exception, and never fall back to Python. + opened = False if not opened: _print_desktop_error("The default browser could not open Nanobot Desktop.") return 3 @@ -160,7 +173,8 @@ def _interactive_shell() -> bool: def _python_target_label() -> str: - return str(Path(sys.executable).resolve(strict=False)) + # Resolving a venv's symlink points at the base interpreter, losing identity. + return os.path.abspath(sys.executable) def _print_python_target() -> None: @@ -193,7 +207,7 @@ def _desktop_terminal_directory() -> Path | None: if sys.platform == "darwin": root = os.environ.get("NANOBOT_DESKTOP_ROOT", "").strip() base = Path(root).expanduser() if root else Path.home() / "Library/Application Support/Nanobot" - return base / "terminal" + return base.absolute() / "terminal" if sys.platform == "win32": override = os.environ.get("NANOBOT_DESKTOP_DATA_DIR", "").strip() local_app_data = override or os.environ.get("LOCALAPPDATA", "").strip() @@ -202,7 +216,7 @@ def _desktop_terminal_directory() -> Path | None: base = Path(os.path.expandvars(local_app_data)).expanduser() if not override: base /= "Nanobot" - return base / "terminal" + return base.absolute() / "terminal" return None @@ -217,7 +231,10 @@ def _read_private_descriptor(directory: Path, descriptor: Path) -> bytes: raise DesktopTargetError("Desktop descriptor could not be read") from exc else: directory_flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) - file_flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0) + file_flags = ( + os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0) + | getattr(os, "O_NOFOLLOW", 0) + ) try: directory_fd = os.open(directory, directory_flags) except OSError as exc: @@ -339,16 +356,21 @@ def _desktop_webui_url(reply: DesktopReply) -> str: raise DesktopTargetError(f"Desktop is not ready ({reply.state})") if "webui" not in reply.capabilities or not reply.webui_url: raise DesktopTargetError("Desktop does not advertise WebUI attachment") - if reply.webui_url != reply.webui_url.strip() or any( + if "\\" in reply.webui_url or reply.webui_url != reply.webui_url.strip() or any( ord(character) < 0x20 or ord(character) == 0x7F for character in reply.webui_url ): raise DesktopTargetError("Desktop returned an invalid WebUI URL") - parsed = urlsplit(reply.webui_url) + try: + parsed = urlsplit(reply.webui_url) + port = parsed.port # Validate invalid/out-of-range ports before browser handoff. + except ValueError as exc: + raise DesktopTargetError("Desktop returned an invalid WebUI URL") from exc if ( parsed.scheme != "http" or parsed.hostname not in {"127.0.0.1", "localhost", "::1"} or parsed.username is not None or parsed.password is not None + or port == 0 ): raise DesktopTargetError("Desktop returned a non-loopback WebUI URL") return reply.webui_url @@ -367,13 +389,15 @@ def _unix_exchange(address: str, payload: bytes) -> bytes: raise DesktopTargetError("Desktop socket is not private to the current user") client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) - client.settimeout(_PROTOCOL_TIMEOUT_S) + deadline = time.monotonic() + _PROTOCOL_TIMEOUT_S try: + client.settimeout(_remaining_seconds(deadline)) client.connect(address) if not _peer_is_current_user(client): raise DesktopTargetError("Desktop socket peer identity did not match") + client.settimeout(_remaining_seconds(deadline)) client.sendall(payload) - return _read_socket_line(client) + return _read_socket_line(client, deadline=deadline) finally: client.close() @@ -395,14 +419,17 @@ def _peer_is_current_user(client: socket.socket) -> bool: return uid == os.geteuid() -def _read_socket_line(client: socket.socket) -> bytes: +def _remaining_seconds(deadline: float) -> float: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise DesktopTargetError("Desktop response timed out") + return remaining + + +def _read_socket_line(client: socket.socket, *, deadline: float) -> bytes: data = bytearray() - deadline = time.monotonic() + _PROTOCOL_TIMEOUT_S while len(data) <= _MAX_MESSAGE_BYTES: - remaining = deadline - time.monotonic() - if remaining <= 0: - raise DesktopTargetError("Desktop response timed out") - client.settimeout(remaining) + client.settimeout(_remaining_seconds(deadline)) chunk = client.recv(min(1024, _MAX_MESSAGE_BYTES + 1 - len(data))) if not chunk: break @@ -486,13 +513,16 @@ def _windows_pipe_request(address: str, payload: bytes) -> bytes: generic_write = 0x40000000 open_existing = 3 file_flag_overlapped = 0x40000000 + # Permit identity checks, but never let the pipe server impersonate us. + security_identification = 0x00010000 + security_sqos_present = 0x00100000 error_io_pending = 997 wait_object_0 = 0 invalid_handle = ctypes.c_void_p(-1).value pipe_name = rf"\\.\pipe\{address}" deadline = time.monotonic() + _PROTOCOL_TIMEOUT_S - remaining_ms = max(1, int((deadline - time.monotonic()) * 1000)) + remaining_ms = max(1, int(_remaining_seconds(deadline) * 1000)) if not kernel32.WaitNamedPipeW(pipe_name, remaining_ms): raise DesktopTargetError("Desktop named pipe is unavailable") handle = kernel32.CreateFileW( @@ -501,20 +531,22 @@ def _windows_pipe_request(address: str, payload: bytes) -> bytes: 0, None, open_existing, - file_flag_overlapped, + file_flag_overlapped | security_sqos_present | security_identification, None, ) if handle == invalid_handle: raise DesktopTargetError("Desktop named pipe could not be opened") def transfer(function: Any, buffer: Any, size: int) -> int: + _remaining_seconds(deadline) event = kernel32.CreateEventW(None, True, False, None) if not event: raise DesktopTargetError("Desktop named pipe event could not be created") + overlapped = Overlapped() + overlapped.hEvent = event + transferred = wintypes.DWORD() + pending = False try: - overlapped = Overlapped() - overlapped.hEvent = event - transferred = wintypes.DWORD() complete = function( handle, buffer, @@ -525,19 +557,28 @@ def _windows_pipe_request(address: str, payload: bytes) -> bytes: if not complete and ctypes.get_last_error() != error_io_pending: raise DesktopTargetError("Desktop named pipe I/O failed") if not complete: - wait_ms = max(1, int((deadline - time.monotonic()) * 1000)) + pending = True + wait_ms = max(1, int(_remaining_seconds(deadline) * 1000)) if kernel32.WaitForSingleObject(event, wait_ms) != wait_object_0: - kernel32.CancelIoEx(handle, ctypes.byref(overlapped)) raise DesktopTargetError("Desktop named pipe response timed out") if not kernel32.GetOverlappedResult( handle, ctypes.byref(overlapped), ctypes.byref(transferred), False ): raise DesktopTargetError("Desktop named pipe I/O failed") + pending = False return int(transferred.value) finally: + if pending: + # CancelIoEx only requests cancellation. The OS still owns these + # buffers and OVERLAPPED until completion (also on Ctrl+C). + kernel32.CancelIoEx(handle, ctypes.byref(overlapped)) + kernel32.GetOverlappedResult( + handle, ctypes.byref(overlapped), ctypes.byref(transferred), True + ) kernel32.CloseHandle(event) try: + _verify_windows_pipe_owner(handle, kernel32=kernel32) outgoing = ctypes.create_string_buffer(payload) if transfer(kernel32.WriteFile, outgoing, len(payload)) != len(payload): raise DesktopTargetError("Desktop named pipe write was incomplete") @@ -558,3 +599,72 @@ def _windows_pipe_request(address: str, payload: bytes) -> bytes: finally: kernel32.CloseHandle(handle) raise DesktopTargetError("Desktop disconnected or returned an oversized reply") + + +def _verify_windows_pipe_owner(handle: Any, *, kernel32: Any) -> None: + """Authenticate the opened pipe, not its spoofable discovery filename. + + Match the process token's owner SID, as .NET CurrentUserOnly does (including + elevation). No request or bootstrap URL is exchanged before verification. + """ + from ctypes import wintypes + + loader = getattr(ctypes, "WinDLL") + advapi32: Any = loader("advapi32", use_last_error=True) + pointer = ctypes.POINTER(wintypes.LPVOID) + advapi32.GetSecurityInfo.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.DWORD, + pointer, pointer, pointer, pointer, pointer, + ] + advapi32.GetSecurityInfo.restype = wintypes.DWORD + advapi32.OpenProcessToken.argtypes = [ + wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE), + ] + advapi32.OpenProcessToken.restype = wintypes.BOOL + advapi32.GetTokenInformation.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), + ] + advapi32.GetTokenInformation.restype = wintypes.BOOL + advapi32.EqualSid.argtypes = [wintypes.LPVOID, wintypes.LPVOID] + advapi32.EqualSid.restype = wintypes.BOOL + kernel32.GetCurrentProcess.argtypes = [] + kernel32.GetCurrentProcess.restype = wintypes.HANDLE + kernel32.LocalFree.argtypes = [wintypes.LPVOID] + kernel32.LocalFree.restype = wintypes.LPVOID + + owner = wintypes.LPVOID() + security_descriptor = wintypes.LPVOID() + token = wintypes.HANDLE() + se_kernel_object = 6 + owner_security_information = 1 + token_query = 0x0008 + token_owner = 4 + try: + if advapi32.GetSecurityInfo( + handle, se_kernel_object, owner_security_information, + ctypes.byref(owner), None, None, None, ctypes.byref(security_descriptor), + ) != 0 or not owner.value: + raise DesktopTargetError("Desktop named pipe owner could not be verified") + if not advapi32.OpenProcessToken( + kernel32.GetCurrentProcess(), token_query, ctypes.byref(token) + ): + raise DesktopTargetError("Current Windows user could not be verified") + required = wintypes.DWORD() + advapi32.GetTokenInformation(token, token_owner, None, 0, ctypes.byref(required)) + if not 0 < required.value <= 65536: + raise DesktopTargetError("Current Windows user could not be verified") + owner_info = ctypes.create_string_buffer(required.value) + if not advapi32.GetTokenInformation( + token, token_owner, owner_info, len(owner_info), ctypes.byref(required) + ): + raise DesktopTargetError("Current Windows user could not be verified") + # TOKEN_OWNER contains one PSID backed by this token-information buffer. + current_owner = ctypes.cast(owner_info, pointer).contents + if not current_owner.value or not advapi32.EqualSid(owner, current_owner): + raise DesktopTargetError("Desktop named pipe owner is not the current user") + finally: + if token.value: + kernel32.CloseHandle(token) + if security_descriptor.value: + kernel32.LocalFree(security_descriptor) diff --git a/nanobot/cli/entry.py b/nanobot/cli/entry.py index 6adfc2443..972a25b23 100644 --- a/nanobot/cli/entry.py +++ b/nanobot/cli/entry.py @@ -79,7 +79,7 @@ def main() -> None: dispatch_args = ["agent", *agent_args] if agent_args is not None else raw_args set_cli_process_identity(dispatch_args) _configure_windows_console() - if not shell_completion: + if not shell_completion and not raw_args: from nanobot.cli.desktop_target import dispatch_bare_desktop_target desktop_exit = dispatch_bare_desktop_target(raw_args) diff --git a/tests/cli/test_desktop_target.py b/tests/cli/test_desktop_target.py index 69cf07040..e644474fd 100644 --- a/tests/cli/test_desktop_target.py +++ b/tests/cli/test_desktop_target.py @@ -3,6 +3,7 @@ import os import socket import tempfile import threading +import time from pathlib import Path import pytest @@ -53,6 +54,18 @@ def test_macos_discovery_uses_private_versioned_descriptor(monkeypatch, tmp_path assert discover_desktop_target() == DesktopTarget(instance_id, "unix", address) +def test_relative_desktop_root_matches_absolute_advertised_address(monkeypatch, tmp_path): + instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" + terminal = tmp_path / "terminal" + address = str(terminal / "connect-v1.sock") + _write_descriptor(terminal, instance_id=instance_id, transport="unix", address=address) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(desktop_target.sys, "platform", "darwin") + monkeypatch.setenv("NANOBOT_DESKTOP_ROOT", ".") + assert discover_desktop_target() == DesktopTarget(instance_id, "unix", address) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions") def test_discovery_rejects_non_private_directory(monkeypatch, tmp_path: Path) -> None: instance_id = "0b47107a-cd31-4711-b1ca-3b53dcedf90a" terminal = tmp_path / "terminal" @@ -98,11 +111,13 @@ def test_unix_request_revalidates_instance_identity() -> None: server.bind(str(address)) address.chmod(0o600) server.listen(1) + server.settimeout(2) received: list[dict[str, object]] = [] def serve() -> None: client, _ = server.accept() with client: + client.settimeout(2) request = client.makefile("rb").readline() received.append(json.loads(request)) client.sendall( @@ -273,3 +288,117 @@ def test_disconnect_after_desktop_selection_never_falls_back(monkeypatch, capsys assert dispatch_bare_desktop_target(["webui"]) == 3 assert calls == 2 assert "No backend was started" in capsys.readouterr().err + + +@pytest.mark.parametrize("args", [[], ["webui"]]) +@pytest.mark.parametrize("state", ["busy", "unavailable", "offline", "untrusted"]) +def test_unready_desktop_preserves_python_before_selection(monkeypatch, capsys, args, state): + class Target: + def request(self, _operation): + if state == "offline": + raise DesktopTargetError("stale socket") + return DesktopReply(state, frozenset({"webui"})) + + def discover(): + if state == "untrusted": + raise DesktopTargetError("unsafe descriptor") + return Target() + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", discover) + monkeypatch.setattr( + desktop_target, "_choose_target", lambda _: pytest.fail("not a usable Desktop target") + ) + assert dispatch_bare_desktop_target(args) is None + output = capsys.readouterr() + assert "Using current Python environment:" in output.out + assert "No backend was started" not in output.err + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX venv executable symlinks") +def test_python_label_preserves_venv_executable(monkeypatch, tmp_path): + interpreter = tmp_path / "python" + interpreter.symlink_to(desktop_target.sys.executable) + monkeypatch.setattr(desktop_target.sys, "executable", str(interpreter)) + assert desktop_target._python_target_label() == str(interpreter) + + +@pytest.mark.parametrize("url", [ + "http://[::1/#/?bootstrapSecret=private", + "http://localhost:invalid/#/?bootstrapSecret=private", + "http://localhost:99999/", + "http://localhost:0/", + "http://evil.example\\@localhost/", + "http://localhost\\evil.example/", + "http://localhost/\n", +]) +def test_invalid_browser_urls_are_protocol_errors(url): + with pytest.raises(DesktopTargetError): + _desktop_webui_url(DesktopReply("ready", frozenset({"webui"}), url)) + + +def test_browser_failure_does_not_leak_bootstrap_or_fall_back(monkeypatch, capsys): + url = "http://localhost:8765/#/?bootstrapSecret=private" + + class Target: + def request(self, _operation): + return DesktopReply("ready", frozenset({"webui"}), url) + + def fail_browser(_url): + raise OSError(f"Could not open {url}") + + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr(desktop_target, "discover_desktop_target", Target) + monkeypatch.setattr(desktop_target, "_choose_target", lambda _: "desktop") + monkeypatch.setattr("nanobot.cli.webui_support._launch_browser", fail_browser) + assert dispatch_bare_desktop_target(["webui"]) == 3 + output = capsys.readouterr() + assert "bootstrapSecret" not in output.out + output.err + assert "Using current Python" not in output.out + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX discovery file types") +@pytest.mark.parametrize("kind", ["fifo", "symlink"]) +def test_discovery_rejects_special_files_without_blocking(monkeypatch, tmp_path, kind): + terminal = tmp_path / "terminal" + terminal.mkdir(mode=0o700) + descriptor = terminal / "instance-v1.json" + if kind == "fifo": + os.mkfifo(descriptor, mode=0o600) + else: + other = tmp_path / "other" + other.write_text("{}") + descriptor.symlink_to(other) + monkeypatch.setattr(desktop_target.sys, "platform", "darwin") + monkeypatch.setenv("NANOBOT_DESKTOP_ROOT", str(tmp_path)) + with pytest.raises(DesktopTargetError): + discover_desktop_target() + + +@pytest.mark.skipif(os.name == "nt", reason="Unix socketpair") +def test_socket_response_timeout_is_bounded(): + client, server = socket.socketpair() + with client, server, pytest.raises(TimeoutError): + desktop_target._read_socket_line(client, deadline=time.monotonic() + 0.02) + + +@pytest.mark.skipif(os.name == "nt", reason="Unix socketpair") +@pytest.mark.parametrize("reply", [b"{}", b"x" * 17]) +def test_socket_rejects_truncated_or_oversized_reply(monkeypatch, reply): + monkeypatch.setattr(desktop_target, "_MAX_MESSAGE_BYTES", 16) + client, server = socket.socketpair() + with client, server: + server.sendall(reply) + server.shutdown(socket.SHUT_WR) + with pytest.raises(DesktopTargetError): + desktop_target._read_socket_line(client, deadline=time.monotonic() + 1) + + +@pytest.mark.parametrize("args", [[], ["webui"]]) +def test_completion_never_discovers_desktop(monkeypatch, args): + monkeypatch.setenv("_NANOBOT_COMPLETE", "complete_bash") + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr( + desktop_target, "discover_desktop_target", lambda: pytest.fail("completion must bypass") + ) + assert dispatch_bare_desktop_target(args) is None diff --git a/tests/cli/test_desktop_target_entrypoints.py b/tests/cli/test_desktop_target_entrypoints.py new file mode 100644 index 000000000..70f7c38ec --- /dev/null +++ b/tests/cli/test_desktop_target_entrypoints.py @@ -0,0 +1,62 @@ +"""The picker covers retained launchers without intercepting explicit commands.""" + +import pytest +from typer.testing import CliRunner + +from nanobot.cli import commands, desktop_target, entry + + +@pytest.mark.parametrize("args", [[], ["webui"]]) +def test_retained_launcher_attaches_without_starting_python(monkeypatch, args): + seen = [] + + def dispatch(raw): + seen.append(raw) + return 0 + + monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", dispatch) + monkeypatch.setattr(entry, "_run_agent", lambda *_a, **_kw: pytest.fail("agent started")) + # Callback exits before webui can inspect/load config or start its runtime. + monkeypatch.setattr( + "nanobot.cli.webui._resolve_webui_config_path", + lambda *_a, **_kw: pytest.fail("Python WebUI started"), + ) + result = CliRunner().invoke(commands.app, args) + assert result.exit_code == 0, result.output + assert seen == [args] + + +@pytest.mark.parametrize("args", [["agent", "--help"], ["--help"], ["--version"], + ["webui", "--no-open"], ["webui", "--port", "8765"]]) +def test_retained_launcher_explicit_commands_never_discover(monkeypatch, args): + monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True) + monkeypatch.setattr( + desktop_target, "discover_desktop_target", lambda: pytest.fail("explicit discovery") + ) + class PythonWebuiReachedError(Exception): + pass + + def stop_webui(*_args, **_kwargs): + raise PythonWebuiReachedError + + monkeypatch.setattr("nanobot.cli.webui._resolve_webui_config_path", stop_webui) + result = CliRunner().invoke(commands.app, args) + if args[0] == "webui": + assert isinstance(result.exception, PythonWebuiReachedError), result.output + else: + assert result.exit_code == 0, result.output + + +def test_modern_webui_invocation_prompts_once(monkeypatch): + calls = [] + + def dispatch(args): + calls.append(args) + return 0 + + monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", dispatch) + monkeypatch.setattr(entry.sys, "argv", ["nanobot", "webui"]) + with pytest.raises(SystemExit) as exc: + entry.main() + assert exc.value.code == 0 + assert calls == [["webui"]] diff --git a/tests/cli/test_desktop_target_windows.py b/tests/cli/test_desktop_target_windows.py new file mode 100644 index 000000000..e25147b00 --- /dev/null +++ b/tests/cli/test_desktop_target_windows.py @@ -0,0 +1,164 @@ +"""Win32 boundary tests; native pipe integration additionally runs on Windows.""" + +import ctypes +import os +import threading +import uuid +from ctypes import wintypes +from unittest.mock import MagicMock + +import pytest + +from nanobot.cli import desktop_target +from nanobot.cli.desktop_target import DesktopTargetError + + +def _set_pointer(pointer, value, value_type=wintypes.LPVOID): + ctypes.cast(pointer, ctypes.POINTER(value_type)).contents.value = value + + +@pytest.fixture +def kernel(monkeypatch): + api = MagicMock() + api.WaitNamedPipeW.return_value = True + api.CreateFileW.return_value = 11 + api.CreateEventW.return_value = 12 + monkeypatch.setattr(ctypes, "WinDLL", lambda *_a, **_kw: api, raising=False) + monkeypatch.setattr(ctypes, "get_last_error", lambda: 997, raising=False) + monkeypatch.setattr(desktop_target, "_verify_windows_pipe_owner", lambda *_a, **_kw: None) + return api + + +def test_windows_pipe_authenticates_before_io(monkeypatch, kernel): + def deny(*_args, **_kwargs): + raise DesktopTargetError("wrong owner") + + monkeypatch.setattr(desktop_target, "_verify_windows_pipe_owner", deny) + with pytest.raises(DesktopTargetError, match="wrong owner"): + desktop_target._windows_pipe_request("local-test", b"request\n") + kernel.WriteFile.assert_not_called() + kernel.ReadFile.assert_not_called() + kernel.CloseHandle.assert_called_once_with(11) + # No impersonation/delegation; only allow identifying the connecting user. + assert kernel.CreateFileW.call_args.args[5] == 0x40110000 + assert kernel.CreateFileW.call_args.args[0] == r"\\.\pipe\local-test" + + +@pytest.mark.parametrize("failure", ["timeout", "interrupt", "deadline"]) +def test_windows_pending_io_is_drained_before_buffers_are_freed(monkeypatch, kernel, failure): + lifecycle = [] + kernel.WriteFile.return_value = False + kernel.WaitForSingleObject.return_value = 258 # WAIT_TIMEOUT + if failure == "interrupt": + kernel.WaitForSingleObject.side_effect = KeyboardInterrupt + elif failure == "deadline": + # Whole request budget: wait-pipe, pre-transfer, then pending wait. + monkeypatch.setattr( + desktop_target, "_remaining_seconds", + MagicMock(side_effect=[1.0, 0.5, DesktopTargetError("timed out")]), + ) + kernel.CancelIoEx.side_effect = lambda *_: lifecycle.append("cancel") or True + kernel.GetOverlappedResult.side_effect = ( + lambda _h, _o, _n, wait: lifecycle.append(("drain", wait)) or False + ) + kernel.CloseHandle.side_effect = lambda handle: lifecycle.append(("close", handle)) + expected = KeyboardInterrupt if failure == "interrupt" else DesktopTargetError + with pytest.raises(expected): + desktop_target._windows_pipe_request("local-test", b"request\n") + assert lifecycle == ["cancel", ("drain", True), ("close", 12), ("close", 11)] + + +def test_windows_synchronous_io_cannot_restart_expired_budget(monkeypatch, kernel): + def write(_handle, _buffer, size, count, _overlapped): + _set_pointer(count, size, wintypes.DWORD) + return True + + kernel.WriteFile.side_effect = write + monkeypatch.setattr( + desktop_target, "_remaining_seconds", + MagicMock(side_effect=[1.0, 0.5, DesktopTargetError("timed out")]), + ) + with pytest.raises(DesktopTargetError, match="timed out"): + desktop_target._windows_pipe_request("local-test", b"request\n") + kernel.ReadFile.assert_not_called() + kernel.CancelIoEx.assert_not_called() + + +@pytest.mark.parametrize("same_user", [False, True]) +def test_windows_owner_sid_is_checked_and_handles_released(monkeypatch, same_user): + kernel = MagicMock() + security = MagicMock() + kernel.GetCurrentProcess.return_value = -1 + + def security_info(_handle, object_type, fields, owner, _g, _d, _s, descriptor): + assert object_type == 6 and fields == 1 + _set_pointer(owner, 101) + _set_pointer(descriptor, 102) + return 0 + + def open_token(_process, access, token): + assert access == 8 + _set_pointer(token, 13) + return True + + def token_info(_token, kind, buffer, _length, required): + assert kind == 4 # TOKEN_OWNER matches .NET CurrentUserOnly, including elevation. + _set_pointer(required, 64, wintypes.DWORD) + if buffer is None: + return False + _set_pointer(buffer, 101 if same_user else 201) + return True + + security.GetSecurityInfo.side_effect = security_info + security.OpenProcessToken.side_effect = open_token + security.GetTokenInformation.side_effect = token_info + security.EqualSid.side_effect = lambda owner, user: owner.value == user.value + monkeypatch.setattr(ctypes, "WinDLL", lambda *_a, **_kw: security, raising=False) + if same_user: + desktop_target._verify_windows_pipe_owner(11, kernel32=kernel) + else: + with pytest.raises(DesktopTargetError, match="not the current user"): + desktop_target._verify_windows_pipe_owner(11, kernel32=kernel) + security.EqualSid.assert_called_once() + assert kernel.CloseHandle.call_args.args[0].value == 13 + assert kernel.LocalFree.call_args.args[0].value == 102 + + +@pytest.mark.skipif(os.name != "nt", reason="Requires native Windows named pipes") +def test_native_windows_pipe_roundtrip(): + # _winapi is bundled with CPython on Windows; no test/runtime dependency. + winapi = pytest.importorskip("_winapi") + address = f"nanobot-desktop-v1-{uuid.uuid4()}" + handle = winapi.CreateNamedPipe( + rf"\\.\pipe\{address}", + winapi.PIPE_ACCESS_DUPLEX | winapi.FILE_FLAG_OVERLAPPED, + 0, # PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT + 1, 8192, 8192, 1000, None, + ) + connected = winapi.ConnectNamedPipe(handle, overlapped=True) + received = [] + failures = [] + + def serve(): + try: + connected.GetOverlappedResult(True) + pending, _ = winapi.ReadFile(handle, 8192, True) + pending.GetOverlappedResult(True) + received.append(pending.getbuffer()) + pending, _ = winapi.WriteFile(handle, b'{"state":"ready"}\n', True) + pending.GetOverlappedResult(True) + except OSError as exc: + failures.append(exc) + + thread = threading.Thread(target=serve, daemon=True) + thread.start() + try: + assert desktop_target._windows_pipe_request(address, b"status\n") == b'{"state":"ready"}' + thread.join(timeout=2) + assert not thread.is_alive() + assert received == [b"status\n"] + assert not failures + finally: + connected.cancel() + winapi.CloseHandle(handle) + thread.join(timeout=2) diff --git a/tests/cli/test_entry.py b/tests/cli/test_entry.py index 861ade34e..ca1c1c0f4 100644 --- a/tests/cli/test_entry.py +++ b/tests/cli/test_entry.py @@ -87,7 +87,7 @@ def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None: def test_desktop_handled_bare_invocation_does_not_start_python(monkeypatch) -> None: from nanobot.cli import desktop_target - monkeypatch.setattr(entry.sys, "argv", ["nanobot", "webui"]) + monkeypatch.setattr(entry.sys, "argv", ["nanobot"]) monkeypatch.setattr(entry, "set_cli_process_identity", lambda _args: None) monkeypatch.setattr(entry, "_configure_windows_console", lambda: None) monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", lambda _args: 0)