feat(cli): attach terminal clients to the selected Desktop [skip ci]
NAN-104 requires terminal chat and browser attachment without granting a client ownership of Desktop's gateway. Resolve bounded short-lived credentials over authenticated current-user IPC, pin both Desktop and gateway identities, and reject replacement instances or incompatible clients before any mutation. Reuse the existing TUI artifact resolver behind a narrow Desktop-only entrypoint, keep credentials out of argv/environment/files, and preserve Python-mode reconnect and gateway leases. Add protocol, real-gateway, and anonymous IPC regression coverage; matching native-host and Windows acceptance remain release gates.
This commit is contained in:
1 parent
b373a95f5c
commit
48e7c4f697
20 files changed
+797
-52
No files matched your search
@@ -263,10 +263,10 @@ def test_desktop_tui_selection_fails_without_fallback(monkeypatch, capsys) -> No
|
||||
monkeypatch.setattr(desktop_target, "discover_desktop_target", Target)
|
||||
monkeypatch.setattr(desktop_target, "_choose_target", lambda _status: "desktop")
|
||||
|
||||
assert dispatch_bare_desktop_target([]) == 4
|
||||
assert calls == ["status", "status"]
|
||||
assert dispatch_bare_desktop_target([]) == 3
|
||||
assert calls == ["status", "tui"]
|
||||
error = capsys.readouterr().err
|
||||
assert "does not yet provide attach-only terminal chat" in error
|
||||
assert "unavailable or incompatible" in error
|
||||
assert "No backend was started" in error
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.cli import desktop_target, desktop_tui, tui_launcher
|
||||
from nanobot.cli.desktop_target import DesktopReply, DesktopTargetError
|
||||
|
||||
DESKTOP_ID = "d4f6cc96-a3a2-4a68-9a45-cec04b79ab53"
|
||||
GATEWAY_ID = "d4f6cc96-a3a2-4a68-9a45-cec04b79ab54"
|
||||
|
||||
|
||||
def connection(**overrides):
|
||||
return {
|
||||
"protocolVersion": 1, "gatewayId": GATEWAY_ID,
|
||||
"apiUrl": "http://127.0.0.1:8765", "wsUrl": "ws://127.0.0.1:8765/ws",
|
||||
"wsToken": "synthetic-ws-token", "apiToken": "synthetic-api-token", **overrides,
|
||||
}
|
||||
|
||||
|
||||
def target(**overrides):
|
||||
value = MagicMock(instance_id=DESKTOP_ID)
|
||||
value.request.return_value = DesktopReply("ready", frozenset({"tui"}), tui=connection(**overrides))
|
||||
return value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("overrides", [
|
||||
{"protocolVersion": True}, {"protocolVersion": 2}, {"gatewayId": "not-a-uuid"},
|
||||
{"wsUrl": "ws://evil.example/ws"}, {"apiUrl": "https://127.0.0.1:8765"},
|
||||
{"apiUrl": "http://localhost:8765"}, {"apiUrl": "http://127.0.0.1:0"},
|
||||
{"wsUrl": "ws://127.0.0.1:8766/ws"}, {"wsUrl": "ws://127.0.0.1:8765/ws?token=hidden"},
|
||||
{"wsUrl": "ws://user@127.0.0.1:8765/ws"}, {"wsUrl": "ws://127.0.0.1:8765/ws#fragment"},
|
||||
{"apiUrl": "http://127.0.0.1:8765/api"}, {"apiToken": ""}, {"wsToken": "secret\n"},
|
||||
])
|
||||
def test_resolver_rejects_unusable_or_unsafe_connection(monkeypatch, overrides):
|
||||
monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: target(**overrides))
|
||||
with pytest.raises(DesktopTargetError):
|
||||
desktop_tui.resolve_request(json.dumps({"instanceId": DESKTOP_ID, "gatewayId": GATEWAY_ID}).encode())
|
||||
|
||||
|
||||
def test_resolver_revalidates_both_instances_for_each_refresh(monkeypatch):
|
||||
chosen = target()
|
||||
monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: chosen)
|
||||
request = json.dumps({"instanceId": DESKTOP_ID, "gatewayId": GATEWAY_ID}).encode()
|
||||
assert desktop_tui.resolve_request(request) == connection()
|
||||
assert desktop_tui.resolve_request(request) == connection()
|
||||
assert chosen.request.call_count == 2
|
||||
chosen.instance_id = "replacement"
|
||||
with pytest.raises(DesktopTargetError, match="disconnected"):
|
||||
desktop_tui.resolve_request(request)
|
||||
chosen.instance_id = DESKTOP_ID
|
||||
chosen.request.return_value = DesktopReply("ready", frozenset({"tui"}), tui=connection(gatewayId=DESKTOP_ID))
|
||||
with pytest.raises(DesktopTargetError, match="identity changed"):
|
||||
desktop_tui.resolve_request(request)
|
||||
|
||||
|
||||
def test_launcher_has_no_gateway_ownership_and_no_credentials_in_child_env(monkeypatch):
|
||||
chosen = target()
|
||||
monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: ["terminal-client"])
|
||||
monkeypatch.setattr(tui_launcher, "_ensure_gateway", lambda *a, **k: pytest.fail("must not own gateway"))
|
||||
monkeypatch.setenv("NANOBOT_TUI_GATEWAY_STOP_COMMAND", "forbidden stop")
|
||||
monkeypatch.setenv("NANOBOT_TUI_BOOTSTRAP_SECRET", "unrelated-bootstrap")
|
||||
monkeypatch.setenv("NANOBOT_TUI_WS_URL", "ws://unrelated")
|
||||
monkeypatch.delenv("NANOBOT_DESKTOP_CLIENT_CACHE", raising=False)
|
||||
calls = []
|
||||
process = MagicMock()
|
||||
process.wait.return_value = 90
|
||||
process.poll.return_value = 90
|
||||
monkeypatch.setattr(desktop_tui.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, b"1\n", b""))
|
||||
def start(args, **kw):
|
||||
calls.append((args, kw))
|
||||
return process
|
||||
monkeypatch.setattr(desktop_tui.subprocess, "Popen", start)
|
||||
assert desktop_tui.launch_desktop_tui(chosen) == 0
|
||||
args, options = calls[0]
|
||||
assert args == ["terminal-client"]
|
||||
env = options["env"]
|
||||
assert set(key for key in env if key.startswith("NANOBOT_TUI_")) == {
|
||||
"NANOBOT_TUI_DESKTOP_TARGET", "NANOBOT_TUI_DESKTOP_RESOLVER",
|
||||
}
|
||||
assert "synthetic" not in json.dumps((args, options))
|
||||
assert "unrelated-bootstrap" not in json.dumps((args, options))
|
||||
assert json.loads(env["NANOBOT_TUI_DESKTOP_TARGET"])["gatewayId"] == GATEWAY_ID
|
||||
resolver = json.loads(env["NANOBOT_TUI_DESKTOP_RESOLVER"])
|
||||
assert resolver[:3] == [sys.executable, "-I", "-S"]
|
||||
assert resolver[-1] == "--resolve"
|
||||
process.terminate.assert_not_called()
|
||||
|
||||
|
||||
def test_unsupported_desktop_does_not_install_or_launch_a_client(monkeypatch):
|
||||
chosen = target()
|
||||
chosen.request.return_value = DesktopReply("ready", frozenset({"webui"}))
|
||||
monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: pytest.fail("unsupported target"))
|
||||
with pytest.raises(DesktopTargetError):
|
||||
desktop_tui.launch_desktop_tui(chosen)
|
||||
|
||||
|
||||
def test_incompatible_tui_fails_without_fallback(monkeypatch):
|
||||
monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: ["old-client"])
|
||||
monkeypatch.setattr(desktop_tui.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 1, b"", b""))
|
||||
monkeypatch.setattr(desktop_tui.subprocess, "Popen", lambda *a, **kw: pytest.fail("cannot start client"))
|
||||
with pytest.raises(DesktopTargetError, match="does not support"):
|
||||
desktop_tui.launch_desktop_tui(target())
|
||||
|
||||
|
||||
def test_bare_command_uses_attachment_and_preserves_return_code(monkeypatch):
|
||||
chosen = target()
|
||||
monkeypatch.setattr(desktop_target, "_interactive_shell", lambda: True)
|
||||
monkeypatch.setattr(desktop_target, "discover_desktop_target", lambda: chosen)
|
||||
monkeypatch.setattr(desktop_target, "_choose_target", lambda status: "desktop")
|
||||
monkeypatch.setattr(desktop_tui, "launch_desktop_tui", lambda selected: 17 if selected is chosen else 99)
|
||||
assert desktop_target.dispatch_bare_desktop_target([]) == 17
|
||||
|
||||
|
||||
def test_standalone_resolver_is_silent_on_invalid_input(tmp_path):
|
||||
script = str(Path(desktop_tui.__file__).resolve())
|
||||
result = subprocess.run([sys.executable, "-I", "-S", script, "--resolve"],
|
||||
input=b'{"apiToken":"synthetic"}\n', capture_output=True, timeout=5)
|
||||
assert result.returncode == 3
|
||||
assert result.stdout == result.stderr == b""
|
||||
with (tmp_path / "not-a-pipe").open("wb") as output:
|
||||
result = subprocess.run([sys.executable, "-I", "-S", script, "--resolve"],
|
||||
input=b"{}\n", stdout=output, stderr=subprocess.PIPE, timeout=5)
|
||||
assert result.returncode == 3
|
||||
assert (tmp_path / "not-a-pipe").read_bytes() == b""
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Bun Unix socket-pair stdout")
|
||||
def test_resolver_output_accepts_only_anonymous_ipc(tmp_path):
|
||||
first, second = socket.socketpair()
|
||||
with first, second:
|
||||
assert desktop_tui._anonymous_output(first.fileno())
|
||||
read_fd, write_fd = os.pipe()
|
||||
try:
|
||||
assert desktop_tui._anonymous_output(write_fd)
|
||||
finally:
|
||||
os.close(read_fd)
|
||||
os.close(write_fd)
|
||||
with (tmp_path / "file").open("wb") as file:
|
||||
assert not desktop_tui._anonymous_output(file.fileno())
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
with socket.create_connection(listener.getsockname()) as client:
|
||||
peer, _ = listener.accept()
|
||||
with peer:
|
||||
assert not desktop_tui._anonymous_output(client.fileno())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("args", [["--config", "elsewhere"], ["gateway", "stop"], ["--help"], ["webui"]])
|
||||
def test_desktop_only_entry_never_forwards_unknown_commands(args, monkeypatch):
|
||||
monkeypatch.setattr(sys, "argv", ["nanobot-desktop-tui", *args])
|
||||
monkeypatch.setattr(desktop_tui, "discover_desktop_target", lambda: pytest.fail("explicit command"))
|
||||
with pytest.raises(SystemExit) as error:
|
||||
desktop_tui.main()
|
||||
assert error.value.code == 2
|
||||
|
||||
|
||||
def test_desktop_cache_avoids_default_python_data_root(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("NANOBOT_DESKTOP_CLIENT_CACHE", str(tmp_path))
|
||||
observed = []
|
||||
def resolve(**kwargs):
|
||||
observed.append(kwargs)
|
||||
raise tui_launcher.TuiUnavailableError("not installed")
|
||||
monkeypatch.setattr(tui_launcher, "resolve_tui_command", resolve)
|
||||
with pytest.raises(DesktopTargetError):
|
||||
desktop_tui.launch_desktop_tui(target())
|
||||
assert observed == [{"data_dir": tmp_path}]
|
||||
@@ -18,7 +18,7 @@ from nanobot.cli.tui_launcher import (
|
||||
_initial_tui_chat_id,
|
||||
_initial_tui_workspace,
|
||||
_resolve_source_tui_command,
|
||||
_resolve_tui_command,
|
||||
resolve_tui_command,
|
||||
_websocket_chat_id,
|
||||
launch_tui,
|
||||
)
|
||||
@@ -103,7 +103,7 @@ def test_launcher_passes_the_canonical_model_preset_to_the_tui(
|
||||
assert wait_for_stop is False
|
||||
released.append(True)
|
||||
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
def ensure_gateway(*args: object, **kwargs: object) -> SimpleNamespace:
|
||||
assert events == ["spawned"]
|
||||
assert kwargs["wait_until_ready"] is False
|
||||
@@ -173,7 +173,7 @@ def test_launcher_terminates_the_tui_when_gateway_start_fails(
|
||||
def fail_gateway(*args: object, **kwargs: object) -> None:
|
||||
raise RuntimeError("gateway failed")
|
||||
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.tui_launcher.subprocess.Popen",
|
||||
lambda *args, **kwargs: FakeProcess(),
|
||||
@@ -227,7 +227,7 @@ def test_launcher_keeps_the_tui_alive_while_an_existing_gateway_recovers(
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime)
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr(
|
||||
"nanobot.cli.tui_launcher.subprocess.Popen",
|
||||
lambda *args, **kwargs: FakeProcess(),
|
||||
@@ -286,7 +286,7 @@ def test_launcher_promotes_the_gateway_when_the_tui_detaches(
|
||||
events.append("waited")
|
||||
return tui_launcher._TUI_DETACH_EXIT_CODE
|
||||
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher._resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"])
|
||||
def popen(command: list[str], *, env: dict[str, str]) -> FakeProcess:
|
||||
assert command == ["nanobot-tui"]
|
||||
captured.update(env)
|
||||
@@ -325,7 +325,7 @@ def test_explicit_tui_binary_must_exist(
|
||||
missing = tmp_path / "missing"
|
||||
monkeypatch.setenv("NANOBOT_TUI_BIN", str(missing))
|
||||
with pytest.raises(TuiUnavailableError, match="does not exist"):
|
||||
_resolve_tui_command()
|
||||
resolve_tui_command()
|
||||
|
||||
|
||||
def test_windows_arm64_fails_instead_of_using_the_classic_prompt(
|
||||
@@ -336,7 +336,7 @@ def test_windows_arm64_fails_instead_of_using_the_classic_prompt(
|
||||
monkeypatch.setattr("nanobot.cli.tui_launcher.platform.machine", lambda: "ARM64")
|
||||
|
||||
with pytest.raises(TuiUnavailableError, match="Windows ARM64"):
|
||||
_resolve_tui_command()
|
||||
resolve_tui_command()
|
||||
|
||||
|
||||
def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun(
|
||||
@@ -357,7 +357,7 @@ def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun(
|
||||
)
|
||||
|
||||
with pytest.raises(TuiUnavailableError, match="source checkout requires Bun"):
|
||||
_resolve_tui_command()
|
||||
resolve_tui_command()
|
||||
|
||||
|
||||
def test_source_checkout_requires_project_and_tui_markers(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Terminal capability metadata is authenticated and does not allocate tokens."""
|
||||
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from websockets.datastructures import Headers
|
||||
from websockets.http11 import Request
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.webui.gateway_tokens import GatewayTokenStore
|
||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
||||
|
||||
|
||||
def test_terminal_probe_is_private_stable_and_does_not_issue_credentials():
|
||||
handler = object.__new__(GatewayHTTPHandler)
|
||||
handler.config = WebSocketConfig(token_issue_secret="fixture-secret")
|
||||
handler.tokens = GatewayTokenStore(max_tokens=0)
|
||||
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
|
||||
request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"}))
|
||||
assert handler._handle_bootstrap(connection, request, terminal_probe=True).status_code == 401
|
||||
request.headers["X-Nanobot-Auth"] = "fixture-secret"
|
||||
for _ in range(3):
|
||||
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
|
||||
assert response.status_code == 200
|
||||
assert json.loads(response.body) == {
|
||||
"protocolVersion": 1, "gatewayId": handler.tokens.instance_id,
|
||||
}
|
||||
assert "no-store" in response.headers["Cache-Control"]
|
||||
assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens
|
||||
assert GatewayTokenStore().instance_id != handler.tokens.instance_id
|
||||
@@ -211,6 +211,55 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
|
||||
_stop_gateway(process)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_path: Path) -> None:
|
||||
"""Two terminal clients exercise real authentication, framing and gateway lifetime."""
|
||||
ws_port, gateway_port = _free_port(), _free_port()
|
||||
workspace = tmp_path / "workspace"
|
||||
workspace.mkdir()
|
||||
config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"
|
||||
_write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)
|
||||
process = _start_gateway(config_path, log_path)
|
||||
base_url = f"http://127.0.0.1:{ws_port}"
|
||||
try:
|
||||
first = _wait_for_bootstrap(base_url, process, log_path)
|
||||
terminal = first["terminal"]
|
||||
assert terminal["protocolVersion"] == 1
|
||||
unauthenticated = httpx.get(f"{base_url}/webui/terminal", trust_env=False)
|
||||
assert unauthenticated.status_code == 401
|
||||
probe = _get_bootstrap(f"{base_url}/webui/terminal")
|
||||
assert probe == terminal # Contains no token or config information.
|
||||
second = _get_bootstrap(f"{base_url}/webui/bootstrap")
|
||||
assert second["terminal"] == terminal
|
||||
identity_query = f'&terminal_protocol=1&terminal_instance={terminal["gatewayId"]}'
|
||||
first_url = f'{first["ws_url"]}?token={first["token"]}&client_id=terminal-one'
|
||||
# A rejected wrong-instance upgrade must not consume the one-use WS token.
|
||||
with pytest.raises(websockets.exceptions.InvalidStatus) as wrong:
|
||||
async with websockets.connect(first_url + "&terminal_protocol=1&terminal_instance=wrong"):
|
||||
pytest.fail("Wrong gateway identity accepted")
|
||||
assert wrong.value.response.status_code == 409
|
||||
async with websockets.connect(first_url + identity_query) as one:
|
||||
assert (await _recv_until(one, "ready"))["terminal"] == terminal
|
||||
second_url = f'{second["ws_url"]}?token={second["token"]}&client_id=terminal-two'
|
||||
async with websockets.connect(second_url + identity_query) as two:
|
||||
assert (await _recv_until(two, "ready"))["terminal"] == terminal
|
||||
await one.close()
|
||||
await two.send(json.dumps({"type": "new_chat"}))
|
||||
chat_id = (await _recv_until(two, "attached"))["chat_id"]
|
||||
await two.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "/model", "webui": True, "turn_id": "terminal-model"}))
|
||||
assert "custom/smoke-model" in (await _recv_until(two, "message"))["text"]
|
||||
await _recv_until(two, "turn_end")
|
||||
assert process.poll() is None
|
||||
after = _get_bootstrap(f"{base_url}/webui/bootstrap")
|
||||
assert after["terminal"] == terminal
|
||||
# The ordinary WebUI ready frame remains unchanged (no opt-in metadata).
|
||||
async with websockets.connect(f'{after["ws_url"]}?token={after["token"]}&client_id=browser') as browser:
|
||||
assert "terminal" not in await _recv_until(browser, "ready")
|
||||
finally:
|
||||
_stop_gateway(process)
|
||||
|
||||
|
||||
def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
|
||||
Reference in new issue
Block a user