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.
This commit is contained in:
Xubin Ren committed 2026-09-08 10:04:15 +08:00
1 parent 8fe0c62d68
commit dba77b5e74
8 files changed
+529 -43

No files matched your search

+129
View File
@@ -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
@@ -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"]]
+164
View File
@@ -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)
+1 -1
View File
@@ -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)