feat(webui): complete remote pairing and connection recovery

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 11889c018e
commit 192ca6e49e
52 files changed
+7313 -675

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
"""Server pairing suggests a real login account, never blindly trusts SUDO_USER."""
from types import SimpleNamespace
import pytest
from nanobot.cli import remote
@pytest.mark.parametrize(
("uid", "sudo_user", "expected"),
[(1001, "other", "ubuntu"), (0, "ubuntu", "ubuntu"),
(0, "missing", None), (0, "nanobot", None), (0, "root", None)],
)
def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expected):
pwd = pytest.importorskip("pwd")
users = [SimpleNamespace(pw_name=name, pw_uid=user_uid, pw_shell=shell) for name, user_uid, shell in
[("root", 0, "/bin/bash"), ("ubuntu", 1001, "/bin/bash"),
("other", 1002, "/bin/bash"), ("nanobot", 1003, "/usr/sbin/nologin")]]
monkeypatch.setattr(remote.os, "getuid", lambda: uid)
monkeypatch.setattr(pwd, "getpwuid", lambda _: users[1] if uid else users[0])
monkeypatch.setattr(pwd, "getpwall", lambda: users)
monkeypatch.setenv("SUDO_USER", sudo_user)
assert remote._default_ssh_user() == expected
@pytest.mark.parametrize(("connection", "expected"), [
("1.1.1.1 50000 8.8.8.8 22", "8.8.8.8"),
("1.1.1.1 50000 10.0.0.8 22", ""),
("1.1.1.1 50000 127.0.0.1 22", ""),
("1.1.1.1 50000 not-an-ip 22", ""), ("", ""),
])
def test_only_global_ssh_server_address_can_be_suggested(monkeypatch, connection, expected):
monkeypatch.setenv("SSH_CONNECTION", connection)
assert remote._default_host() == expected
+48
View File
@@ -110,3 +110,51 @@ async def test_pick_native_folder_wraps_process_start_failure(tmp_path, monkeypa
with pytest.raises(picker.NativeFolderPickerError, match="failed to start"):
await picker.pick_native_folder()
@pytest.mark.parametrize("result", ["file", "directory", "cancel"])
async def test_pick_native_file_returns_only_existing_file_path(tmp_path, monkeypatch, result):
selected = tmp_path / "ssh-config"
selected.write_text("must-not-be-read-or-returned")
output = str(selected if result == "file" else tmp_path)
command = _picker_command(tmp_path, "raise SystemExit(1)" if result == "cancel" else f"print({output!r})")
monkeypatch.setattr(picker, "_picker_command", lambda kind: command)
if result == "directory":
with pytest.raises(picker.NativeFolderPickerError, match="invalid file"):
await picker.pick_native_file()
else:
assert await picker.pick_native_file() == (str(selected) if result == "file" else None)
@pytest.mark.parametrize("platform,marker", [
("darwin", "choose file"), ("win32", "OpenFileDialog"), ("linux", "--file-selection"),
])
def test_file_picker_uses_platform_file_dialog(monkeypatch, platform, marker):
monkeypatch.setattr(picker.sys, "platform", platform)
monkeypatch.setattr(picker.shutil, "which", lambda executable: executable)
monkeypatch.setenv("DISPLAY", ":test")
command = picker._picker_command("file")
assert command is not None
assert marker in " ".join(command.argv)
assert "--directory" not in command.argv
def test_file_picker_is_unavailable_on_headless_linux(monkeypatch):
monkeypatch.setattr(picker.sys, "platform", "linux")
monkeypatch.delenv("DISPLAY", raising=False)
monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)
assert picker._picker_command("file") is None
async def test_file_picker_cancellation_reaps_process(monkeypatch):
import asyncio
from unittest.mock import AsyncMock, MagicMock
process = MagicMock(returncode=None)
process.communicate = AsyncMock(side_effect=asyncio.CancelledError)
process.wait = AsyncMock(return_value=0)
monkeypatch.setattr(picker, "_picker_command", lambda kind: picker._PickerCommand(("picker",), frozenset()))
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
with pytest.raises(asyncio.CancelledError):
await picker.pick_native_file()
process.terminate.assert_called_once()
+54
View File
@@ -9,18 +9,72 @@ import subprocess
import sys
import time
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
from urllib.parse import quote
import httpx
import pytest
import websockets
from nanobot.config.loader import load_config
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import PENDING_USER_TURN_KEY, RUNTIME_CHECKPOINT_KEY
from nanobot.webui.remote_proxy import RemoteProxy
from nanobot.webui.remote_ssh import Tunnel
_BOOTSTRAP_SECRET = "smoke-secret"
async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(tmp_path: Path) -> None:
"""The auth proxy must preserve the actual gateway's WebUI mutation audience."""
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)
proxy = None
try:
upstream = _wait_for_bootstrap(f"http://127.0.0.1:{ws_port}", process, log_path)
# The real gateway already owns this private listener. SSH pipe ownership
# and shutdown are exercised separately by test_remote_proxy/remote_tunnel.
transport = MagicMock(spec=Tunnel, port=ws_port, active=True,
pause=AsyncMock(), close=AsyncMock())
proxy = await RemoteProxy.open(transport, _BOOTSTRAP_SECRET, upstream["terminal"]["gatewayId"])
async with httpx.AsyncClient(trust_env=False) as client:
first = (await client.get(proxy.origin + "/webui/bootstrap", headers={
"X-Nanobot-Auth": proxy.secret,
})).json()
assert _BOOTSTRAP_SECRET not in json.dumps(first)
async with websockets.connect(first["ws_url"] + "?token=" + first["token"] + "&client_id=proxy-smoke") as ws:
assert (await _recv_until(ws, "ready"))["client_id"] == "proxy-smoke"
await ws.send(json.dumps({"type": "new_chat"}))
chat_id = (await _recv_until(ws, "attached"))["chat_id"]
await _recv_until(ws, "session_updated")
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
"content": "/model", "webui": True, "turn_id": "proxy-turn"}))
assert "custom/smoke-model" in (await _recv_until(ws, "message"))["text"]
await _recv_until(ws, "turn_end")
await ws.send(json.dumps({"type": "webui_request", "request_id": "proxy-settings",
"action": "settings.runtime_config.update",
"payload": {"values": {"agents.defaults.max_tool_iterations": 2}}}))
mutation = await _recv_until(ws, "webui_response")
assert mutation["ok"] is True, mutation
assert load_config(config_path).agents.defaults.max_tool_iterations == 2
renewed = (await client.get(proxy.origin + "/webui/bootstrap", headers={
"X-Nanobot-Auth": proxy.secret,
})).json()
assert renewed["token"] != first["token"]
response = await client.get(proxy.origin + "/api/sessions", headers={
"Authorization": "Bearer " + renewed["api_token"],
})
assert f"websocket:{chat_id}" in {row["key"] for row in response.json()["sessions"]}
finally:
if proxy is not None:
await proxy.close()
_stop_gateway(process)
def _free_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(("127.0.0.1", 0))
+144
View File
@@ -0,0 +1,144 @@
"""Remote setup discovers metadata, not secrets, and never invents sudo access."""
import asyncio
import json
import os
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.webui import remote_discovery, remote_ssh
from nanobot.webui.remote_instances import RemoteInstances
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile
if sys.platform != "win32":
import pwd
def locate(monkeypatch, capsys, path, units="", properties=""):
calls = []
def systemctl(args, **kwargs):
calls.append(args)
assert args[0] == "systemctl" and "sudo" not in args
assert kwargs["timeout"] == 2
return SimpleNamespace(returncode=0, stdout=units if "list-units" in args else properties)
monkeypatch.setattr(sys, "argv", ["locate", str(path)])
monkeypatch.setattr(subprocess, "run", systemctl)
exec(remote_discovery._LOCATE, {})
result = json.loads(capsys.readouterr().out.split("NANOBOT_REMOTE:")[1])
assert "model-secret" not in json.dumps(result)
return result, calls
def test_default_config_found_without_reading_contents(tmp_path, monkeypatch, capsys):
path = tmp_path / "config.json"
path.write_text("model-secret") # Even invalid config content isn't read by discovery.
result, calls = locate(monkeypatch, capsys, path)
assert result["candidates"] == [{"config_path": str(path), "runtime_user": "", "service": ""}]
assert len(calls) == 1
@pytest.mark.skipif(sys.platform == "win32", reason="systemd account discovery targets Unix servers")
def test_service_account_and_private_path_are_offered_without_sudo(tmp_path, monkeypatch, capsys):
path = tmp_path / ".nanobot/config.json"
original_stat = Path.stat
def stat(self, *args, **kwargs):
if self == path:
raise PermissionError
return original_stat(self, *args, **kwargs)
monkeypatch.setattr(Path, "stat", stat)
monkeypatch.setattr(pwd, "getpwnam", lambda name: SimpleNamespace(pw_dir=str(tmp_path)))
result, calls = locate(monkeypatch, capsys, tmp_path / "missing.json",
"nanobot-team.service loaded active running\n",
"Id=nanobot-team.service\nUser=nanobot\nWorkingDirectory=/opt/nanobot\nExecStart=/opt/nanobot/bin/nanobot gateway\n")
assert result["candidates"] == [{"config_path": str(path), "runtime_user": "nanobot", "service": "nanobot-team.service"}]
assert len(calls) == 2
@pytest.mark.skipif(sys.platform == "win32", reason="systemd account discovery targets Unix servers")
def test_multiple_configs_and_custom_service_path(tmp_path, monkeypatch, capsys):
default = tmp_path / "default.json"
custom = tmp_path / "custom config.json"
default.touch()
custom.touch()
user = pwd.getpwuid(os.getuid()).pw_name
result, _ = locate(monkeypatch, capsys, default, "nanobot.service loaded active running\n",
f'Id=nanobot.service\nUser={user}\nWorkingDirectory={tmp_path}\nExecStart=nanobot gateway --config "custom config.json"\n')
assert [item["config_path"] for item in result["candidates"]] == [str(default), str(custom)]
assert all(not item["runtime_user"] for item in result["candidates"])
def test_unavailable_systemctl_keeps_default_result(tmp_path, monkeypatch, capsys):
monkeypatch.setattr(sys, "argv", ["locate", str(tmp_path / "absent")])
monkeypatch.setattr(subprocess, "run", MagicMock(side_effect=FileNotFoundError))
exec(remote_discovery._LOCATE, {})
result = json.loads(capsys.readouterr().out.split("NANOBOT_REMOTE:")[1])
assert result["candidates"] == []
assert result["incomplete"] is True
async def test_inspection_uses_login_user_and_strips_unexpected_data(monkeypatch):
check = AsyncMock(return_value={"hostname": "server", "candidates": [{
"config_path": "/srv/bot/config.json", "runtime_user": "nanobot", "service": "nanobot.service", "secret": "model-secret",
}], "incomplete": False, "secret": "model-secret"})
monkeypatch.setattr(remote_discovery, "run_check", check)
result = await remote_discovery.inspect(RemoteProfile(name="Test", host="server", runtime_user="root"))
assert check.call_args.args[0].runtime_user == ""
assert "model-secret" not in json.dumps(result)
@pytest.mark.parametrize("result", [
{"hostname": "server", "candidates": [{"config_path": "/tmp/x\n", "runtime_user": ""}], "incomplete": False},
{"hostname": "server", "candidates": [{"config_path": "/tmp/x", "runtime_user": "-root"}], "incomplete": False},
{"hostname": "server", "candidates": [{}] * 9, "incomplete": False},
{"hostname": "server", "candidates": "bad", "incomplete": False},
])
async def test_malformed_inspection_is_rejected(monkeypatch, result):
monkeypatch.setattr(remote_discovery, "run_check", AsyncMock(return_value=result))
with pytest.raises(RemoteError, match="probe_failed"):
await remote_discovery.inspect(RemoteProfile(name="Test", host="server"))
async def test_inspection_reuses_host_verification_without_opening_tunnel(tmp_path, monkeypatch):
manager = RemoteInstances(tmp_path)
key = (await manager.action("save", {"profile": {"name": "Test", "host": "server"}}))["id"]
check = AsyncMock(side_effect=RemoteError("host_key_unknown"))
monkeypatch.setattr(remote_discovery, "inspect", check)
with pytest.raises(RemoteError, match="host_key_unknown"):
await manager.action("inspect", {"id": key})
assert key in manager._unknown_hosts
assert not manager.connections
check.side_effect = None
check.return_value = {"hostname": "server", "candidates": [], "incomplete": False}
before = manager.path.read_bytes()
assert (await manager.action("inspect", {"id": key}))["candidates"] == []
assert manager.path.read_bytes() == before
async def test_cancelled_inspection_reaps_remote_process(monkeypatch):
process = MagicMock(returncode=None)
process.communicate = AsyncMock(side_effect=asyncio.CancelledError)
process.wait = AsyncMock(return_value=0)
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
with pytest.raises(asyncio.CancelledError):
await remote_discovery.inspect(RemoteProfile(name="Test", host="server"))
process.terminate.assert_called_once()
@pytest.mark.parametrize(("message", "code"), [
(b"kex_exchange_identification: Connection closed by remote host", "ssh_connection_closed"),
(b"Connection reset by peer", "ssh_connection_closed"),
(b"connect to host server port 22: Connection refused", "ssh_refused"),
(b"Could not resolve hostname server", "ssh_host_not_found"),
(b"Too many authentication failures", "ssh_too_many_keys"),
])
def test_setup_errors_are_actionable_without_leaking_server_output(message, code):
assert remote_ssh.ssh_error(message) == code
+458 -17
View File
@@ -3,6 +3,8 @@
import asyncio
import json
import socket
import subprocess
import sys
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -13,10 +15,17 @@ from websockets.datastructures import Headers
from websockets.http11 import Request
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.webui import remote_ssh
from nanobot.webui import remote_instances, remote_ssh
from nanobot.webui.gateway_services import build_gateway_services
from nanobot.webui.remote_instances import RemoteInstances
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments, ssh_error
from nanobot.webui.remote_proxy import RemoteProxy
from nanobot.webui.remote_ssh import (
RemoteError,
RemoteProfile,
open_tunnel,
ssh_arguments,
ssh_error,
)
@pytest.fixture
@@ -31,8 +40,11 @@ async def save(manager, **values):
@pytest.fixture
def ssh(monkeypatch):
process = SimpleNamespace(returncode=None)
tunnel = SimpleNamespace(process=process, port=23456, close=AsyncMock())
tunnel = SimpleNamespace(active=True, error="", port=23455, pause=AsyncMock(), close=AsyncMock(), resume=MagicMock())
proxy = SimpleNamespace(tunnel=tunnel, port=23456, origin="http://127.0.0.1:23456",
secret="local-capability", pause=tunnel.pause, close=tunnel.close,
resume=MagicMock())
monkeypatch.setattr(RemoteProxy, "open", AsyncMock(return_value=proxy))
probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"})
monkeypatch.setattr(remote_ssh, "probe", probe)
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
@@ -46,7 +58,7 @@ def ssh(monkeypatch):
real_client = httpx.AsyncClient
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
return SimpleNamespace(tunnel=tunnel, probe=probe, state=state)
return SimpleNamespace(tunnel=tunnel, proxy=proxy, probe=probe, state=state, client=real_client)
async def test_save_survives_restart_without_credentials(manager):
@@ -57,6 +69,58 @@ async def test_save_survives_restart_without_credentials(manager):
await save(manager, private_key="must-never-save")
async def test_new_local_manager_has_new_view_identity_for_same_remote(manager, ssh):
key = await save(manager)
first = await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
resumed = await manager.action("connect", {"id": key})
assert resumed["view_id"] == first["view_id"]
restarted = RemoteInstances(manager.path.parent)
second = await restarted.action("connect", {"id": key})
assert second["gateway_id"] == first["gateway_id"]
assert second["view_id"] != first["view_id"]
assert restarted.snapshot()["profiles"][0]["view_id"] == second["view_id"]
assert "view_id" not in manager.path.read_text()
async def test_unchanged_save_allows_retry_after_browser_load_failure(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
before = manager.path.read_bytes()
result = await manager.action("save", {"id": key, "profile": {
"name": "Team", "host": "ubuntu@example.test",
}})
assert result["id"] == key
assert manager.path.read_bytes() == before
ssh.tunnel.pause.assert_not_awaited()
async def test_readding_exact_destination_reuses_entry_without_renaming_or_disconnect(manager, ssh):
key = await save(manager)
before = manager.path.read_bytes()
assert await save(manager, name="Another name") == key
assert manager.path.read_bytes() == before
await manager.action("connect", {"id": key})
before = manager.path.read_bytes()
live = manager.connections[key]
assert await save(manager, name="Still the same instance") == key
assert manager.path.read_bytes() == before
assert manager.connections[key] is live
ssh.tunnel.pause.assert_not_awaited()
ssh.tunnel.close.assert_not_awaited()
@pytest.mark.parametrize("change", [
{"host": "another-alias"}, {"port": 2222}, {"identity_file": "/other/key"},
{"runtime_user": "nanobot"}, {"ssh_config": "/other/config"},
{"config_path": "/srv/another-bot/config.json"},
])
async def test_different_destinations_are_not_collapsed_before_connecting(manager, change):
first = await save(manager)
assert await save(manager, **change) != first
assert len(manager.snapshot()["profiles"]) == 2
@pytest.mark.parametrize("host", ["-oProxyCommand=evil", "user@host;whoami", "a\nb", "$(id)", "host name"])
def test_hosts_cannot_be_shell_or_ssh_options(host):
with pytest.raises(ValidationError):
@@ -66,7 +130,7 @@ def test_hosts_cannot_be_shell_or_ssh_options(host):
def test_strict_ssh_without_agent_forwarding(monkeypatch):
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "/usr/bin/ssh")
args = ssh_arguments(RemoteProfile(name="Team", host="my-alias"))
for option in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ForwardAgent=no", "ControlPath=none", "PermitLocalCommand=no", "ExitOnForwardFailure=yes"]:
for option in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ForwardAgent=no", "ControlPath=none", "PermitLocalCommand=no", "ExitOnForwardFailure=yes", "RemoteCommand=none"]:
assert option in args
assert "StrictHostKeyChecking=no" not in args
@@ -77,10 +141,12 @@ async def test_connect_checks_protocol_and_only_disconnects_tunnel(manager, ssh)
assert connection["hostname"] == "team-host"
assert connection["gateway_id"] == "remote-one"
assert connection["url"].startswith("http://127.0.0.1:23456/#/?bootstrapSecret=")
assert "private-webui-secret" not in json.dumps(connection)
assert "private-webui-secret" not in json.dumps(manager.snapshot())
assert "private-webui-secret" not in manager.path.read_text()
await manager.action("disconnect", {"id": key})
ssh.tunnel.close.assert_awaited_once()
ssh.tunnel.pause.assert_awaited_once()
ssh.tunnel.close.assert_not_awaited()
assert not manager.snapshot()["profiles"][0]["connected"]
assert len(manager.snapshot()["profiles"]) == 1
@@ -99,15 +165,91 @@ async def test_bad_target_closes_tunnel_and_never_returns_launch_url(manager, ss
assert not manager.connections
async def test_failed_initial_retries_do_not_accumulate_listeners(manager, ssh, monkeypatch):
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(wraps=open_tunnel))
key = await save(manager)
ssh.state["status"] = 404
for _ in range(8):
with pytest.raises(RemoteError, match="incompatible_gateway"):
await manager.action("connect", {"id": key})
assert not manager._proxies
assert json.loads(manager.path.read_text())[key]["local_port"] == 0
async def test_failed_reconnect_retains_published_origin(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
ssh.state["status"] = 404
with pytest.raises(RemoteError, match="incompatible_gateway"):
await manager.action("connect", {"id": key})
assert manager._proxies == {23456: ssh.proxy}
ssh.tunnel.close.assert_not_awaited()
@pytest.mark.parametrize("paired", [False, True])
async def test_rejected_pair_key_explains_repair_not_ssh_agent(manager, ssh, monkeypatch, paired):
key = await save(manager)
if paired:
profiles = manager._read()
profiles[key].pair_id = key
manager._write(profiles)
monkeypatch.setattr(manager.pairing, "connection", lambda _: ssh.probe.return_value)
ssh.tunnel.error = "ssh_auth_failed"
def reject(_):
raise httpx.ReadError("SSH authentication rejected")
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
transport=httpx.MockTransport(reject), **kwargs,
))
with pytest.raises(RemoteError, match="pair_authorization_rejected" if paired else "ssh_auth_failed"):
await manager.action("connect", {"id": key})
assert not manager.connections
ssh.tunnel.close.assert_awaited_once()
async def test_server_restart_requires_reconnect_not_local_fallback(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
ssh.state["identity"]["gatewayId"] = "restarted"
assert not (await manager.health())["profiles"][0]["connected"]
profile = (await manager.health())["profiles"][0]
assert not profile["connected"]
assert profile["connection_error"] == "instance_changed"
assert profile["gateway_id"] == "remote-one"
assert key in manager.connections
ssh.tunnel.close.assert_not_awaited()
@pytest.mark.parametrize(("status", "identity", "error"), [
(401, {}, "remote_auth_failed"),
(403, {}, "remote_auth_failed"),
(200, {"protocolVersion": 2, "gatewayId": "remote-one"}, "incompatible_gateway"),
(200, {"protocolVersion": True, "gatewayId": "remote-one"}, "incompatible_gateway"),
(200, [], "incompatible_gateway"),
])
async def test_health_reports_actionable_safe_errors(manager, ssh, status, identity, error):
key = await save(manager)
await manager.action("connect", {"id": key})
ssh.state.update(status=status, identity=identity)
profile = (await manager.health())["profiles"][0]
assert profile["connection_error"] == error
assert not profile["connected"]
assert "private-webui-secret" not in json.dumps(profile)
async def test_explicit_disconnect_is_not_a_network_failure(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
assert (await manager.health())["profiles"][0]["connection_error"] == "disconnected"
await manager.action("connect", {"id": key})
profile = (await manager.health())["profiles"][0]
assert profile["connected"]
assert not profile.get("connection_error")
async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh):
manager.local_gateway_id = "remote-one"
key = await save(manager)
@@ -117,12 +259,39 @@ async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh):
assert not manager.connections
@pytest.mark.parametrize("gateway_id", ["remote-one", "another-instance"])
async def test_aliases_cannot_open_duplicate_views_but_distinct_instances_can(manager, ssh, monkeypatch, gateway_id):
first = await save(manager)
await manager.action("connect", {"id": first})
first_connection = manager.connections[first]
alias = await save(manager, host="another-alias", config_path="/srv/bot/config.json")
# A genuinely separate tunnel/proxy, rather than the shared fixture handle.
second_tunnel = SimpleNamespace(active=True, error="", port=23457, close=AsyncMock())
second_proxy = SimpleNamespace(port=23458, origin="http://127.0.0.1:23458", secret="local-two")
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=second_tunnel))
monkeypatch.setattr(RemoteProxy, "open", AsyncMock(return_value=second_proxy))
ssh.state["identity"]["gatewayId"] = gateway_id
if gateway_id == "remote-one":
with pytest.raises(RemoteError, match="duplicate_instance"):
await manager.action("connect", {"id": alias})
second_tunnel.close.assert_awaited_once()
RemoteProxy.open.assert_not_awaited()
assert alias not in manager.connections
else:
assert (await manager.action("connect", {"id": alias}))["gateway_id"] == gateway_id
second_tunnel.close.assert_not_awaited()
assert manager.connections[first] is first_connection
ssh.tunnel.pause.assert_not_awaited()
ssh.tunnel.close.assert_not_awaited()
async def test_forget_only_removes_saved_profile(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
await manager.action("remove", {"id": key})
assert manager.snapshot()["profiles"] == []
ssh.tunnel.close.assert_awaited_once()
ssh.tunnel.pause.assert_awaited_once()
ssh.tunnel.close.assert_not_awaited()
async def test_closing_local_manager_reaps_ssh(manager, ssh):
@@ -142,6 +311,78 @@ async def test_refresh_reuses_a_healthy_tunnel(manager, ssh):
ssh.tunnel.close.assert_not_awaited()
async def test_reconnect_resumes_reserved_listener(manager, ssh):
key = await save(manager)
first = await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
second = await manager.action("connect", {"id": key})
assert first["url"] == second["url"]
remote_ssh.open_tunnel.assert_awaited_once()
ssh.tunnel.resume.assert_called_once()
ssh.tunnel.close.assert_not_awaited()
async def test_shutdown_does_not_release_origin_during_health_request(manager, ssh, monkeypatch):
key = await save(manager)
await manager.action("connect", {"id": key})
entered, release = asyncio.Event(), asyncio.Event()
async def respond(request):
entered.set()
await release.wait()
ssh.tunnel.close.assert_not_awaited()
assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
return httpx.Response(200, json=ssh.state["identity"])
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
transport=httpx.MockTransport(respond), **kwargs,
))
health = asyncio.create_task(manager.health())
await asyncio.wait_for(entered.wait(), 2)
shutdown = asyncio.create_task(manager.close())
try:
await asyncio.sleep(0)
assert not shutdown.done()
ssh.tunnel.close.assert_not_awaited()
finally:
release.set()
await asyncio.gather(health, shutdown)
ssh.tunnel.close.assert_awaited_once()
async def test_health_deadline_returns_editable_offline_directory(manager, ssh, monkeypatch):
key = await save(manager)
await manager.action("connect", {"id": key})
cancelled = asyncio.Event()
async def respond(request):
try:
await asyncio.Event().wait()
finally:
cancelled.set()
monkeypatch.setattr(remote_instances, "_HEALTH_TIMEOUT_SECONDS", 0.02)
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
transport=httpx.MockTransport(respond), **kwargs,
))
directory = await asyncio.wait_for(manager.health(), 1)
assert not directory["profiles"][0]["connected"]
assert cancelled.is_set()
await manager.action("save", {"id": key, "profile": {
"name": "Repaired", "host": "ubuntu@example.test",
}})
assert manager.snapshot()["profiles"][0]["name"] == "Repaired"
async def test_health_budget_includes_waiting_for_connection_lock(manager, ssh, monkeypatch):
key = await save(manager)
await manager.action("connect", {"id": key})
monkeypatch.setattr(remote_instances, "_HEALTH_TIMEOUT_SECONDS", 0.02)
async with manager._lock:
directory = await asyncio.wait_for(manager.health(), 1)
assert directory["profiles"][0]["id"] == key
async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
@@ -160,6 +401,110 @@ async def test_corrupt_store_not_overwritten(manager):
assert manager.path.read_text() == "corrupt"
@pytest.mark.parametrize("change", [
{"config_path": "/srv/other-bot/config.json"},
{"runtime_user": "other-bot"},
{"identity_file": "/tmp/other-identity"},
])
async def test_changing_instance_drops_origin_but_keeps_server_trust(manager, ssh, change):
key = await save(manager)
await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
known_hosts = manager.path.parent / "remote-hosts" / key
known_hosts.parent.mkdir()
known_hosts.write_text("nanobot-remote ssh-ed25519 fixture\n")
await manager.action("save", {"id": key, "profile": {
"name": "Another bot", "host": "ubuntu@example.test", **change,
}})
assert json.loads(manager.path.read_text())[key]["local_port"] == 0
assert known_hosts.read_text() == "nanobot-remote ssh-ed25519 fixture\n"
@pytest.mark.parametrize("failure", ["process-exit", "health-error"])
async def test_offline_profile_can_be_edited_without_hidden_disconnect(manager, ssh, failure):
key = await save(manager)
await manager.action("connect", {"id": key})
if failure == "process-exit":
ssh.tunnel.active = False
else:
ssh.state["status"] = 503
assert not (await manager.health())["profiles"][0]["connected"]
await manager.action("save", {"id": key, "profile": {"name": "Fixed", "host": "fixed.example.test"}})
ssh.tunnel.pause.assert_awaited_once()
assert key not in manager.connections
assert manager.snapshot()["profiles"][0]["host"] == "fixed.example.test"
async def test_live_profile_still_requires_explicit_disconnect_before_edit(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
with pytest.raises(RemoteError, match="disconnect_before_edit"):
await manager.action("save", {"id": key, "profile": {"name": "Changed", "host": "other.test"}})
ssh.tunnel.close.assert_not_awaited()
async def test_retired_origins_survive_edit_forget_and_restart(manager, ssh, monkeypatch):
key = await save(manager)
await manager.action("connect", {"id": key})
await manager.action("disconnect", {"id": key})
await manager.action("save", {"id": key, "profile": {
"name": "Other instance", "host": "ubuntu@example.test", "config_path": "/srv/b/config.json",
}})
restarted = RemoteInstances(manager.path.parent)
async def different_origin(*args, local_port, excluded_ports):
assert local_port == 0
assert 23456 in excluded_ports
ssh.proxy.port = 23457
return ssh.proxy
monkeypatch.setattr(RemoteProxy, "open", different_origin)
await restarted.action("connect", {"id": key})
await restarted.action("remove", {"id": key})
assert restarted.snapshot()["profiles"] == []
restarted_again = RemoteInstances(manager.path.parent)
assert restarted_again._remember_origins({}) == {23456, 23457}
assert "private-webui-secret" not in (manager.path.parent / "remote-origin-ports.json").read_text()
async def test_old_profile_origin_is_remembered_before_first_edit(manager, ssh):
key = await save(manager)
old = json.loads(manager.path.read_text())
old[key]["local_port"] = 23456
manager.path.write_text(json.dumps(old)) # Pre-ledger profile created by the previous build.
await manager.action("save", {"id": key, "profile": {
"name": "Other", "host": "ubuntu@example.test", "runtime_user": "other-user",
}})
assert RemoteInstances(manager.path.parent)._remember_origins({}) == {23456}
async def test_legacy_transparent_origin_is_not_reused(manager, ssh):
key = await save(manager)
old = json.loads(manager.path.read_text())
old[key]["local_port"] = 12345
manager.path.write_text(json.dumps(old))
await manager.action("connect", {"id": key})
kwargs = RemoteProxy.open.call_args.kwargs
assert kwargs["local_port"] == 0
assert 12345 in kwargs["excluded_ports"]
assert json.loads(manager.path.read_text())[key]["proxy_origin"] is True
assert "proxy_origin" not in manager.snapshot()["profiles"][0]
async def test_invalid_origin_ledger_blocks_target_change_without_losing_profile_or_pin(manager):
key = await save(manager)
before = manager.path.read_bytes()
ledger = manager.path.parent / "remote-origin-ports.json"
ledger.write_text('{"corrupt": true}')
known_hosts = manager.path.parent / "remote-hosts" / key
known_hosts.parent.mkdir()
known_hosts.write_text("trusted-key")
with pytest.raises(RemoteError, match="profile_store_invalid"):
await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})
assert manager.path.read_bytes() == before
assert known_hosts.read_text() == "trusted-key"
async def test_new_host_trust_is_explicit_scoped_and_one_use(manager, ssh, monkeypatch):
key = await save(manager)
ssh.probe.side_effect = RemoteError("host_key_unknown")
@@ -199,6 +544,12 @@ async def test_shutdown_prevents_new_tunnels(manager, ssh):
(b"Host key verification failed", "host_key_unknown"),
(b"Permission denied (publickey). secret-information", "ssh_auth_failed"),
(b"timed out with private address", "ssh_unreachable"),
(b"sudo: permission denied for private-user", "runtime_user_denied"),
(b"WARNING: UNPROTECTED PRIVATE KEY FILE! Permission denied", "ssh_key_permissions"),
(b"sign_and_send_pubkey: signing failed for /private/path: agent refused operation\nPermission denied", "ssh_agent_refused"),
(b"/private/config: Bad configuration option: typo", "ssh_config_invalid"),
(b"channel 0: open failed: administratively prohibited: open failed", "ssh_forwarding_denied"),
(b"channel 0: open failed: connect failed: Connection refused", "remote_unreachable"),
])
def test_errors_never_echo_raw_ssh_output(stderr, code):
assert ssh_error(stderr) == code
@@ -214,7 +565,7 @@ def gateway(tmp_path):
)
@pytest.mark.parametrize("action", ["save", "discover", "connect", "remove", "trust"])
@pytest.mark.parametrize("action", ["save", "discover", "inspect", "pick_file", "connect", "remove", "trust"])
async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):
request = Request(f"/api/remote-instances/{action}", Headers())
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
@@ -222,6 +573,56 @@ async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):
assert result.status_code == 405
@pytest.mark.parametrize("path", ["/local/ssh-config", None])
async def test_file_picker_returns_path_without_saving_profile(manager, monkeypatch, path):
from nanobot.webui import native_folder_picker
choose = AsyncMock(return_value=path)
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
assert await manager.action("pick_file", {}) == {"path": path}
assert not manager.path.exists()
choose.assert_awaited_once_with()
async def test_file_picker_failure_does_not_expose_native_error(manager, monkeypatch):
from nanobot.webui import native_folder_picker
monkeypatch.setattr(native_folder_picker, "pick_native_file", AsyncMock(
side_effect=native_folder_picker.NativeFolderPickerError("private diagnostic"),
))
with pytest.raises(RemoteError, match="^file_picker_unavailable$"):
await manager.action("pick_file", {})
async def test_file_picker_does_not_open_multiple_system_dialogs(manager, monkeypatch):
from nanobot.webui import native_folder_picker
choose = AsyncMock()
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
async with manager._picker_lock:
with pytest.raises(RemoteError, match="file_picker_unavailable"):
await manager.action("pick_file", {})
choose.assert_not_awaited()
@pytest.mark.parametrize("peer,host,origin", [
("203.0.113.1", "127.0.0.1:8765", "http://127.0.0.1:8765"),
("127.0.0.1", "bot.example.com", "https://bot.example.com"),
("127.0.0.1", "127.0.0.1:8765", "https://evil.example"),
])
async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch, peer, host, origin):
from nanobot.webui import native_folder_picker
choose = AsyncMock()
monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)
connection = SimpleNamespace(remote_address=(peer, 10000), request=SimpleNamespace(
headers=Headers({"Host": host, "Origin": origin}),
))
result = await gateway.http.dispatch_webui_mutation(connection, "remote.pick_file", {})
assert result.status_code == 403
choose.assert_not_awaited()
@pytest.mark.parametrize(("peer", "host", "origin", "status"), [
("127.0.0.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 200),
("203.0.113.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 403),
@@ -248,6 +649,51 @@ async def test_cancellation_reaps_inflight_probe(monkeypatch):
process.terminate.assert_called_once()
@pytest.mark.parametrize("field", ["trustedProxyAuth", "trusted_proxy_auth"])
def test_ssh_probe_rejects_trusted_assertion_bypass(tmp_path, field):
path = tmp_path / "config.json"
path.write_text(json.dumps({"channels": {"websocket": {
"enabled": True, "tokenIssueSecret": "synthetic-root",
field: {"assertionHeader": "Host", "trustedPeers": ["127.0.0.0/8"]},
}}}))
result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],
capture_output=True, text=True, check=True)
assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1]) == {"error": "incompatible_gateway"}
@pytest.mark.parametrize("banner", [b"", b"Welcome to the server\n", b"{\"port\": 1}\nWelcome without newline"])
async def test_probe_ignores_shell_banners_without_exposing_them(monkeypatch, banner):
data = {"port": 8765, "secret": "synthetic-root"}
process = MagicMock(returncode=0)
process.communicate = AsyncMock(return_value=(
banner + b"\n" + remote_ssh._PROBE_PREFIX + json.dumps(data).encode() + b"\nGoodbye\n", b"",
))
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
assert await remote_ssh.probe(RemoteProfile(name="Test", host="example.test")) == data
@pytest.mark.parametrize("output", [
b"Welcome. Password required for private-user.",
b'\x1eNANOBOT_REMOTE:{"port": 8765, "secret": "s"}\n\x1eNANOBOT_REMOTE:{}',
b"\x1eNANOBOT_REMOTE:not-json-with-private-data",
])
async def test_invalid_probe_protocol_is_not_reported_as_bad_config(monkeypatch, output):
process = MagicMock(returncode=0)
process.communicate = AsyncMock(return_value=(output, b""))
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
with pytest.raises(RemoteError, match="^probe_failed$"):
await remote_ssh.probe(RemoteProfile(name="Test", host="example.test"))
@pytest.mark.parametrize("config", ["invalid JSON", "[]", '{"channels": null}', '{"channels": {"websocket": []}}'])
def test_probe_reports_malformed_config_as_config_error(tmp_path, config):
path = tmp_path / "config.json"
path.write_text(config)
result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],
capture_output=True, text=True, check=True)
assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1]) == {"error": "config_invalid"}
async def test_tunnel_refuses_an_existing_listener(monkeypatch):
spawn = AsyncMock()
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
@@ -263,7 +709,8 @@ async def test_tunnel_refuses_an_existing_listener(monkeypatch):
spawn.assert_not_awaited()
async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch):
@pytest.mark.skipif(hasattr(socket, "SO_EXCLUSIVEADDRUSE"), reason="Unix TIME_WAIT reuse; Windows requires exclusive ownership")
async def test_tunnel_reuses_closed_port_with_time_wait():
with socket.socket() as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 0))
@@ -273,12 +720,6 @@ async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch):
accepted, _ = listener.accept()
accepted.close() # Server-side active close leaves TIME_WAIT after peer closes.
assert peer.recv(1) == b""
process = MagicMock(returncode=None)
process.wait = AsyncMock(return_value=0)
writer = MagicMock()
writer.wait_closed = AsyncMock()
monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
monkeypatch.setattr(asyncio, "open_connection", AsyncMock(return_value=(None, writer)))
tunnel = await remote_ssh.open_tunnel(
RemoteProfile(name="Test", host="example.test"), 8765, local_port=port,
)
+297
View File
@@ -0,0 +1,297 @@
"""Pairing protocol, restricted authorization and local API regression tests."""
import json
import os
import socket
import subprocess
import sys
import threading
import time
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from nanobot.webui import remote_pair_server, remote_pairing, remote_ssh
from nanobot.webui.remote_instances import RemoteInstances
from nanobot.webui.remote_pairing import PairReceipt, PairStore, read_request, seal
from nanobot.webui.remote_ssh import (
PairedSSHProfile,
RemoteError,
ssh_arguments,
transport_arguments,
)
def ssh_public():
return Ed25519PrivateKey.generate().public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode()
def receipt(request, **updates):
return PairReceipt(**dict(id=request.id, ssh_key=request.ssh_key, host="203.0.113.1", user="ubuntu",
ssh_port=22, host_key=ssh_public(), hostname="team", config_path="/srv/nanobot/config.json",
port=8765, secret="private-webui-credential", authorized_until=int(time.time()) + 86400,
**updates))
@pytest.fixture
def pair(tmp_path):
store = PairStore(tmp_path)
start = store.start()
request = read_request(start["command"].split()[-1])
value = receipt(request)
return store, start, request, value, seal(request, value)
def test_round_trip_only_preview_public_fields_and_restart(pair):
store, start, request, value, code = pair
assert "secret" not in json.dumps(start)
assert "private-webui-credential" not in code
preview = store.preview(request.id, code)
assert preview["host"] == "ubuntu@203.0.113.1"
assert "secret" not in json.dumps(preview)
store.finish(request.id, code)
assert PairStore(store.root.parent).connection(request.id)["secret"] == value.secret
assert store.finish(request.id, code) == value
for path in store.path(request.id).iterdir():
assert path.stat().st_mode & 0o777 == 0o600
assert store.path(request.id).stat().st_mode & 0o777 == 0o700
assert value.secret not in (store.path(request.id) / "receipt").read_text()
def test_expiry_and_reconnect_have_distinct_lifetimes(pair, monkeypatch):
store, _, request, _, code = pair
store.finish(request.id, code)
monkeypatch.setattr(remote_pairing.time, "time", lambda: request.expires + 1)
with pytest.raises(RemoteError, match="pair_expired"):
store.preview(request.id, code)
assert store.connection(request.id)["secret"]
def test_wrong_request_and_tampering_fail_closed(pair):
store, _, request, _, code = pair
another = store.start()
for invalid in [code[:-20] + "AAAAAAAAAAAAAAAAAAAA", "garbage", "nbpc1." + "A" * 32769]:
with pytest.raises(RemoteError, match="pair_invalid"):
store.preview(request.id, invalid)
with pytest.raises(RemoteError, match="pair_invalid"):
store.preview(another["id"], code)
assert not (store.path(request.id) / "receipt").exists()
def test_wrapped_console_code_is_accepted(pair):
store, _, request, _, code = pair
wrapped = "\n".join(code[i:i + 80] for i in range(0, len(code), 80))
assert store.preview(request.id, wrapped)["id"] == request.id
@pytest.mark.parametrize("origin", ["http://127.0.0.1:8870", "http://localhost:5173", "http://[::1]:8765"])
def test_return_link_is_loopback_fragment_only_and_survives_new_store(tmp_path, origin):
from urllib.parse import urlsplit
store = PairStore(tmp_path)
started = store.start(origin)
request = read_request(started["command"].split()[-1])
value = receipt(request)
code = seal(request, value)
link = remote_pairing.return_link(request, code)
assert link == origin + "/#/remote?pairing=" + code
assert not urlsplit(link).query
assert "private-webui-credential" not in link
assert PairStore(tmp_path).preview(request.id, code)["host"] == "ubuntu@203.0.113.1"
@pytest.mark.parametrize("origin", ["https://example.com", "http://127.0.0.1.evil.test", "http://127.0.0.1@evil.test", "http://127.0.0.1:0", "http://127.0.0.1:65536", "http://127.0.0.1/path", "http://127.0.0.1?redirect=bad", "http://127.0.0.1#bad", "http://127.0.0.1\n", "http://2130706433", "file:///tmp"])
def test_return_link_rejects_external_or_ambiguous_targets_before_creating_key(tmp_path, origin):
store = PairStore(tmp_path)
with pytest.raises(RemoteError, match="pair_invalid"):
store.start(origin)
assert not store.root.exists()
def test_legacy_request_still_has_copy_code_fallback(pair):
_, _, request, _, code = pair
assert remote_pairing.return_link(request, code) == ""
def test_cancel_only_deletes_pending_pair_files(pair):
store, _, request, _, code = pair
pending = store.start()
store.cancel(pending["id"])
assert not store.path(pending["id"]).exists()
store.finish(request.id, code)
store.cancel(request.id)
assert store.connection(request.id)["secret"]
with pytest.raises(RemoteError):
store.cancel("../../outside")
def test_server_appends_restricted_key_and_revoke_preserves_existing(pair, tmp_path):
_, _, request, _, _ = pair
home = tmp_path / "server-home"
home.mkdir()
(home / ".ssh").mkdir(mode=0o700)
original = ssh_public() + " existing-admin\n"
keys = home / ".ssh/authorized_keys"
keys.write_text(original)
remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)
lines = keys.read_text().splitlines()
assert lines[0] + "\n" == original
assert lines[1].startswith('restrict,expiry-time="')
assert "port-forwarding" not in lines[1]
assert request.ssh_key in lines[1]
assert "private-webui" not in (home / ".ssh/nanobot-remote" / request.id / "bridge.py").read_text()
with pytest.raises(RemoteError, match="pair_used"):
remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)
remote_pair_server.remove_authorization(home, request.id)
assert keys.read_text() == original
remote_pair_server.remove_authorization(home, request.id)
assert keys.read_text() == original
def test_server_refuses_symlink_authorized_keys_without_touching_target(pair, tmp_path):
_, _, request, _, _ = pair
home = tmp_path / "server"
(home / ".ssh").mkdir(parents=True, mode=0o700)
outside = tmp_path / "important"
outside.write_text("untouched")
(home / ".ssh/authorized_keys").symlink_to(outside)
with pytest.raises(OSError):
remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)
assert outside.read_text() == "untouched"
def test_paired_transport_cannot_fall_back_to_generic_probe_or_forwarding(pair, monkeypatch):
store, _, request, value, _ = pair
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "/usr/bin/ssh")
profile = PairedSSHProfile(**store.profile(value).model_dump())
args = ssh_arguments(profile)
assert "IdentityAgent=none" in args and "IdentitiesOnly=yes" in args
assert args[1:3] == ["-F", os.devnull]
transport = transport_arguments(profile, value.port, store.path(request.id) / "known_hosts")
assert "-W" not in transport
assert transport[-1] == "nanobot-remote-bridge"
assert "sudo" not in " ".join(transport)
def test_fixed_bridge_streams_only_to_baked_in_loopback_port():
# Real bidirectional bytes, no SSH_ORIGINAL_COMMAND interpolation.
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(1)
port = listener.getsockname()[1]
def serve():
with listener:
connection, _ = listener.accept()
with connection:
data = bytearray()
while chunk := connection.recv(8192):
data.extend(chunk)
connection.sendall(b"received:" + data)
worker = threading.Thread(target=serve, daemon=True)
worker.start()
result = subprocess.run([sys.executable, "-I", "-S", "-c", remote_pair_server._BRIDGE.replace("PORT", str(port))],
input=b"hello-webui", capture_output=True, timeout=5,
env={**os.environ, "SSH_ORIGINAL_COMMAND": "echo MUST-NOT-EXECUTE"})
worker.join(2)
assert result.returncode == 0
assert result.stdout == b"received:hello-webui"
async def test_api_pair_finalization_pins_host_and_hides_credentials(tmp_path):
manager = RemoteInstances(tmp_path)
started = await manager.action("pair_start", {})
request = read_request(started["command"].split()[-1])
value = receipt(request)
code = seal(request, value)
preview = await manager.action("pair_preview", {"id": request.id, "code": code})
assert "secret" not in preview
result = await manager.action("pair_finish", {"id": request.id, "code": code})
assert result["profiles"][0]["paired"] is True
assert "private-webui" not in json.dumps(result)
assert "private-webui" not in manager.path.read_text()
assert manager._known_hosts(request.id).read_text() == "nanobot-remote " + value.host_key + "\n"
again = await manager.action("pair_finish", {"id": request.id, "code": code})
assert again["id"] == request.id and len(again["profiles"]) == 1
with pytest.raises(RemoteError, match="pair_managed"):
await manager.action("save", {"id": request.id, "profile": manager.pairing.profile(value).model_dump()})
await manager.action("pair_cancel", {"id": request.id})
assert manager.pairing.connection(request.id)["secret"]
await manager.action("remove", {"id": request.id})
assert not manager.pairing.path(request.id).exists()
assert manager.snapshot()["profiles"] == []
def test_model_keys_never_enter_pairing_metadata(tmp_path):
path = tmp_path / "config.json"
path.write_text(json.dumps({"providers": {"deepseek": {"apiKey": "not-exported"}},
"channels": {"websocket": {"enabled": True, "tokenIssueSecret": "webui-only"}}}))
assert "not-exported" not in json.dumps(remote_pair_server.metadata(path))
async def test_route_import_only_copies_network_options(monkeypatch, tmp_path):
config = tmp_path / "config"
config.write_text("")
process = SimpleNamespace(returncode=0, communicate=AsyncMock(return_value=(
b"hostname 203.0.113.1\nuser ubuntu\nport 22\nidentityfile /private/admin-key\nproxycommand nc -b en0 %h %p\nbindaddress none\nbindinterface none\nproxyjump none\n", b"")))
monkeypatch.setattr(remote_ssh.asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
monkeypatch.setattr(remote_ssh, "stop_process", AsyncMock())
profile = remote_ssh.RemoteProfile(name="existing", host="alias", ssh_config=str(config))
route = await remote_ssh.pairing_route(profile, "203.0.113.1")
assert route == "Host *\n proxycommand nc -b en0 %h %p\n"
assert "identity" not in route and "admin" not in route
with pytest.raises(RemoteError, match="pair_route_mismatch"):
await remote_ssh.pairing_route(profile, "different.example")
def test_request_cannot_inject_authorized_keys_options(pair):
_, start, _, _, _ = pair
raw = remote_pairing.unpack("nbpr1.", start["command"].split()[-1])
raw["ssh_key"] = 'command="sh" ' + raw["ssh_key"]
with pytest.raises(RemoteError, match="pair_invalid"):
read_request(remote_pairing.pack("nbpr1.", raw))
def test_expired_device_cannot_connect(pair, monkeypatch):
store, _, request, value, code = pair
store.finish(request.id, code)
monkeypatch.setattr(remote_pairing.time, "time", lambda: value.authorized_until + 1)
with pytest.raises(RemoteError, match="pair_authorization_expired"):
store.connection(request.id)
# The UI can explain expiry without opening a path around connection().
assert store.authorization_until(request.id) == value.authorized_until
def test_authorization_expiry_does_not_hide_other_profiles_on_corrupt_receipt(pair):
store, _, request, _, code = pair
store.finish(request.id, code)
(store.path(request.id) / "receipt").write_text("invalid")
assert store.authorization_until(request.id) is None
with pytest.raises(RemoteError, match="pair_invalid"):
store.connection(request.id)
async def test_saved_pair_exposes_only_expiry_and_public_metadata(pair, monkeypatch):
store, _, request, value, code = pair
manager = RemoteInstances(store.root.parent)
await manager.action("pair_finish", {"id": request.id, "code": code})
monkeypatch.setattr(remote_pairing.time, "time", lambda: value.authorized_until + 1)
profile = manager.snapshot()["profiles"][0]
assert profile["authorized_until"] == value.authorized_until
assert value.secret not in json.dumps(profile)
assert "receipt" not in profile and "exchange_key" not in profile
with pytest.raises(RemoteError, match="pair_authorization_expired"):
await manager.action("connect", {"id": request.id})
def test_failure_before_authorizing_does_not_write_keys(pair, monkeypatch, tmp_path):
_, _, request, value, _ = pair
install = AsyncMock()
monkeypatch.setattr(remote_pair_server, "as_account", install)
with pytest.raises(RemoteError):
remote_pair_server.authorize(request, host=value.host, user=value.user, ssh_port=22,
config=tmp_path / "missing", host_key=value.host_key,
until=value.authorized_until)
install.assert_not_called()
+387
View File
@@ -0,0 +1,387 @@
"""Real browser-side HTTP/WS, real gateway auth, and an owned SSH-pipe fixture."""
import asyncio
import base64
import json
import socket
import sys
import time
from dataclasses import replace
from types import SimpleNamespace
from unittest.mock import MagicMock
from urllib.parse import parse_qs, urlsplit
import httpx
import pytest
from websockets.asyncio.client import connect
from websockets.asyncio.server import serve
from websockets.datastructures import Headers
from websockets.exceptions import InvalidStatus
from websockets.http11 import Request
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.webui import remote_ssh
from nanobot.webui.gateway_services import build_gateway_services
from nanobot.webui.remote_proxy import RemoteProxy
from nanobot.webui.remote_ssh import RemoteProfile, open_tunnel
ROOT = "synthetic-remote-root"
MEDIA = "/api/media/AAAAAAAAAAAAAAAAAAAAAA/remoteFilePayload"
@pytest.fixture
async def remote(tmp_path, monkeypatch):
config = WebSocketConfig(host="127.0.0.1", token_issue_secret=ROOT, path="/custom/ws")
services = build_gateway_services(
config=config, bus=MagicMock(), session_manager=None, static_dist_path=None,
workspace_path=tmp_path, config_path=tmp_path / "config.json",
default_restrict_to_workspace=False, runtime_model_name=None,
runtime_surface="browser", runtime_capabilities_overrides=None,
)
seen, children = [], []
state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False)
async def process(connection, request):
seen.append(request)
path = urlsplit(request.path).path
if path == "/redirect" or (state.ws_redirect and path == config.path):
response = connection.respond(302, "redirect")
response.headers["Location"] = "http://127.0.0.1:1/?token=" + ROOT
response.headers["Set-Cookie"] = "credential=" + ROOT
return response
if path == "/api/fixture" or path == "/api/block":
if not services.tokens.check_api_token(request):
return connection.respond(401, "Unauthorized")
if path == "/api/block":
state.entered.set()
await state.block.wait()
response = connection.respond(200, json.dumps({"text": f"![image]({MEDIA})"}))
response.headers["Content-Type"] = "application/json"
response.headers["Set-Cookie"] = "credential=" + ROOT
return response
if path == MEDIA:
assert request.headers.get("Authorization") is None
response = connection.respond(206, "bytes")
response.headers["Content-Type"] = "image/png"
response.headers["Content-Range"] = "bytes 0-4/10"
return response
return await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)
async def messages(ws):
assert ws in services.endpoint.webui_connections
assert ws.request.headers.get("X-Nanobot-Auth") is None
await ws.send(json.dumps({"ready": True, "media": MEDIA,
"query": parse_qs(urlsplit(ws.request.path).query).get("client_id")}))
async for message in ws:
await ws.send(message)
real_spawn = asyncio.create_subprocess_exec
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
async with serve(messages, "127.0.0.1", 0, process_request=process, max_size=64 * 1024 * 1024) as server:
port = server.sockets[0].getsockname()[1]
pipe = f"""
import os, socket, threading
upstream = socket.create_connection(('127.0.0.1', {port}))
def upload():
while data := os.read(0, 65536):
upstream.sendall(data)
upstream.shutdown(socket.SHUT_WR)
threading.Thread(target=upload, daemon=True).start()
while data := upstream.recv(65536):
os.write(1, data)
"""
async def spawn(*args, **kwargs):
child = await real_spawn(sys.executable, "-u", "-c", pipe, **kwargs)
children.append(child)
return child
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
profile = RemoteProfile(name="Test", host="fixture.test")
tunnel = await open_tunnel(profile, port)
proxy = await RemoteProxy.open(tunnel, ROOT, services.tokens.instance_id)
try:
async with httpx.AsyncClient(trust_env=False) as client:
yield SimpleNamespace(proxy=proxy, tunnel=tunnel, client=client, services=services,
seen=seen, state=state, profile=profile, port=port)
finally:
state.block.set()
await proxy.close()
assert all(child.returncode is not None for child in children)
async def bootstrap(remote, headers=None):
response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers=(
headers or {"X-Nanobot-Auth": remote.proxy.secret}
))
assert response.status_code == 200, response.text
return response.json()
async def test_remote_credentials_never_leave_the_backend(remote):
first, second = await asyncio.gather(bootstrap(remote), bootstrap(remote))
assert first["token"] != second["token"]
for issued in (first, second):
assert ROOT not in json.dumps(issued)
assert issued["token"] not in remote.services.tokens.issued_tokens
assert issued["api_token"] not in remote.services.tokens.api_tokens
assert issued["ws_url"].startswith(f"ws://127.0.0.1:{remote.proxy.port}/remote-session/")
response = await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"], "Cookie": "injected=1",
"X-Forwarded-User": "admin", "X-Forwarded-Host": "evil.test",
})
assert response.status_code == 200
assert MEDIA not in response.text and ROOT not in response.text
assert "set-cookie" not in response.headers
request = remote.seen[-1]
assert request.headers.get("Cookie") is None
assert request.headers.get("X-Forwarded-User") is None
assert request.headers.get("X-Forwarded-Host") is None
assert request.headers["Authorization"] != "Bearer " + issued["api_token"]
@pytest.mark.parametrize("query", ["?token={token}&token=evil", "?%74oken={token}&token=evil"])
async def test_ambiguous_auth_aliases_are_rejected(remote, query):
issued = await bootstrap(remote)
response = await remote.client.get(remote.proxy.origin + "/api/fixture" + query.format(token=issued["api_token"]))
assert response.status_code == 401
async def test_encoded_query_auth_and_case_insensitive_bearer(remote):
issued = await bootstrap(remote, {"authorization": "bearer " + remote.proxy.secret})
response = await remote.client.get(remote.proxy.origin + "/api/fixture?%74oken=" + issued["api_token"])
assert response.status_code == 200
assert "token=" not in remote.seen[-1].path
response = await remote.client.get(remote.proxy.origin + "/api/fixture?token=" + issued["api_token"],
headers={"Authorization": "Bearer " + issued["api_token"]})
assert response.status_code == 401
@pytest.mark.parametrize("headers", [
{"Host": "evil.test"}, {"Origin": "https://evil.test"}, {"Origin": "null"},
])
async def test_foreign_browser_origin_rejected_even_with_local_secret(remote, headers):
response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={
"X-Nanobot-Auth": remote.proxy.secret, **headers,
})
assert response.status_code == 403
assert remote.seen == []
async def test_custom_ws_path_multiple_tabs_and_binary_upload(remote):
issued = await bootstrap(remote)
url = issued["ws_url"] + "?token=" + issued["token"] + "&client_id=original-tab"
async with connect(url, proxy=None, origin=remote.proxy.origin, max_size=64 * 1024 * 1024) as ws:
ready = json.loads(await ws.recv())
assert ready["query"] == ["original-tab"]
assert ready["media"].startswith("/api/media/local/")
binary = bytes(range(256)) * 8192
await ws.send(binary)
assert await ws.recv() == binary
await ws.send(json.dumps({"text": "normal message", "nested": [1, 2]}))
assert json.loads(await ws.recv())["text"] == "normal message"
with pytest.raises(InvalidStatus) as rejected:
async with connect(url, proxy=None):
pass
assert rejected.value.response.status_code == 401
second = await bootstrap(remote)
async with connect(second["ws_url"] + "?token=" + second["token"], proxy=None) as other:
assert json.loads(await other.recv())["ready"] is True
async def test_signed_media_wrapped_over_http_and_websocket_and_range_preserved(remote):
issued = await bootstrap(remote)
response = await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"],
})
local = response.json()["text"].split("(")[1][:-1]
async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:
assert json.loads(await ws.recv())["media"] == local
response = await remote.client.get(remote.proxy.origin + local, headers={"Range": "bytes=0-4"})
assert response.status_code == 206 and response.content == b"bytes"
assert response.headers["content-range"] == "bytes 0-4/10"
assert remote.seen[-1].headers["Range"] == "bytes=0-4"
assert (await remote.client.get(remote.proxy.origin + MEDIA)).status_code == 401
async def test_http_and_websocket_redirects_cannot_disclose_credentials(remote):
response = await remote.client.get(remote.proxy.origin + "/redirect")
assert response.status_code == 502
assert ROOT not in response.text and "location" not in response.headers
assert "set-cookie" not in response.headers
remote.state.ws_redirect = True
issued = await bootstrap(remote)
with pytest.raises(InvalidStatus) as rejected:
async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None):
pass
assert rejected.value.response.status_code == 502
async def test_pause_keeps_origin_and_revokes_grants_but_allows_renewal(remote):
issued = await bootstrap(remote)
await remote.proxy.pause()
with socket.socket() as competitor:
competitor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
with pytest.raises(OSError):
competitor.bind(("127.0.0.1", remote.proxy.port))
competitor.listen()
assert (await remote.client.get(remote.proxy.origin + "/")).status_code == 503
remote.tunnel.resume(remote.profile, remote.port, None)
remote.proxy.resume(ROOT, remote.services.tokens.instance_id)
assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"],
})).status_code == 401
assert (await bootstrap(remote))["ws_url"] == issued["ws_url"]
@pytest.mark.skipif(hasattr(socket, "SO_EXCLUSIVEADDRUSE"), reason="Unix immediate port takeover; Windows keeps exclusive ownership until release")
async def test_shutdown_replay_contains_only_dead_local_capabilities(remote):
issued = await bootstrap(remote)
origin, secret = remote.proxy.origin, remote.proxy.secret
await remote.proxy.close()
received = []
async def replacement(reader, writer):
received.append(await reader.readuntil(b"\r\n\r\n"))
writer.write(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
await writer.drain()
writer.close()
await writer.wait_closed()
# The same browser retries after the local gateway exits. The new process
# receives credentials that the actual remote gateway cannot authenticate.
async with await asyncio.start_server(replacement, "127.0.0.1", remote.proxy.port):
await remote.client.get(origin + "/webui/bootstrap", headers={"X-Nanobot-Auth": secret})
await remote.client.get(origin + "/api/fixture", headers={"Authorization": "Bearer " + issued["api_token"]})
wire = b"".join(received).decode()
assert ROOT not in wire
assert not any(token in wire for token in remote.services.tokens.api_tokens)
assert not any(token in wire for token in remote.services.tokens.issued_tokens)
assert not remote.services.tokens.check_api_token(Request("/api/fixture", Headers({
"Authorization": "Bearer " + issued["api_token"],
})))
async def test_shutdown_cancels_inflight_proxy_requests_before_closing_private_origin(remote):
issued = await bootstrap(remote)
pending = asyncio.create_task(remote.client.get(remote.proxy.origin + "/api/block", headers={
"Authorization": "Bearer " + issued["api_token"],
}))
await asyncio.wait_for(remote.state.entered.wait(), 3)
close = remote.tunnel.close
async def guarded_close():
assert not remote.proxy._tasks
await close()
remote.tunnel.close = guarded_close
await asyncio.wait_for(remote.proxy.close(), 5)
await asyncio.gather(pending, return_exceptions=True)
async def test_configured_token_issuer_cannot_be_used_through_proxy(remote):
remote.services.http.config.token_issue_path = "/assets/token"
remote.proxy.resume(ROOT, remote.services.tokens.instance_id, "/assets/token")
issued = await bootstrap(remote)
for path in ("/assets/token", "/assets/token/", "/assets/token?token=" + issued["api_token"]):
response = await remote.client.get(remote.proxy.origin + path, headers={"X-Nanobot-Auth": remote.proxy.secret})
assert response.status_code == 403
remote.services.http.config.token_issue_path = "/webui/bootstrap"
assert (await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={
"X-Nanobot-Auth": remote.proxy.secret,
})).status_code == 502
async def test_expired_local_tokens_fail_and_renewal_recovers(remote):
issued = await bootstrap(remote)
for grants, token in ((remote.proxy._api, issued["api_token"]), (remote.proxy._ws, issued["token"])):
grants[token] = replace(grants[token], expires=time.monotonic() - 1)
assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"],
})).status_code == 401
with pytest.raises(InvalidStatus) as rejected:
async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None):
pass
assert rejected.value.response.status_code == 401
renewed = await bootstrap(remote)
assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + renewed["api_token"],
})).status_code == 200
async def test_local_restart_rejects_all_old_credentials_and_changes_cache_scope(remote):
issued = await bootstrap(remote)
secret, port = remote.proxy.secret, remote.proxy.port
await remote.proxy.close()
tunnel = await open_tunnel(remote.profile, remote.port)
# A new origin also works on Windows while its old exclusive socket lingers.
remote.proxy = await RemoteProxy.open(tunnel, ROOT, remote.services.tokens.instance_id,
excluded_ports={port})
try:
assert (await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={
"X-Nanobot-Auth": secret,
})).status_code == 401
assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"],
})).status_code == 401
renewed = await bootstrap(remote)
assert urlsplit(renewed["ws_url"]).path != urlsplit(issued["ws_url"]).path
finally:
await remote.proxy.close()
async def test_remote_restart_invalidates_media_and_cache_scope(remote):
issued = await bootstrap(remote)
await remote.client.get(remote.proxy.origin + "/api/fixture", headers={
"Authorization": "Bearer " + issued["api_token"],
})
assert remote.proxy._media_cache
remote.proxy.resume(ROOT, "new-instance")
assert not remote.proxy._media_cache
assert remote.proxy._ws_path != issued["ws_path"]
@pytest.mark.parametrize("path", ["/", "/custom/%61pi"])
async def test_custom_websocket_literal_paths_are_preserved(remote, path):
remote.services.http.config.path = path
issued = await bootstrap(remote)
async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:
assert json.loads(await ws.recv())["ready"] is True
assert any(urlsplit(request.path).path == path for request in remote.seen)
@pytest.mark.parametrize("prefix", ["https://images.example", "//cdn.example", "file:///tmp"])
async def test_external_media_like_urls_remain_unchanged(remote, prefix):
external = prefix + MEDIA
text = f"![external]({external}) and ![local]({MEDIA})"
rewritten = remote.proxy._rewrite(text)
assert external in rewritten
assert rewritten.count("/api/media/local/") == 1
assert len(remote.proxy._media_cache) == 1
async def test_media_cache_eviction_preserves_old_links_and_new_media(remote):
first = remote.proxy._rewrite(MEDIA)
for index in range(10001):
remote.proxy._rewrite(f"/api/media/BBBBBBBBBBBBBBBBBBBBBB/{index}")
assert len(remote.proxy._media_cache) == 10000
assert MEDIA not in remote.proxy._media_cache
assert (await remote.client.get(remote.proxy.origin + first)).status_code == 206
latest = remote.proxy._rewrite(MEDIA)
assert (await remote.client.get(remote.proxy.origin + latest)).status_code == 206
assert MEDIA.encode() not in base64.urlsafe_b64decode(first.rsplit("/", 1)[1])
await remote.proxy.pause()
remote.tunnel.resume(remote.profile, remote.port, None)
remote.proxy.resume(ROOT, remote.services.tokens.instance_id)
assert (await remote.client.get(remote.proxy.origin + first)).status_code == 206
async def test_media_capabilities_reject_tampering_and_other_proxy_keys(remote):
local = remote.proxy._rewrite(MEDIA)
prefix, token = local.rsplit("/", 1)
ciphertext = bytearray(base64.urlsafe_b64decode(token))
ciphertext[40] ^= 1
tampered = prefix + "/" + base64.urlsafe_b64encode(ciphertext).decode()
assert (await remote.client.get(remote.proxy.origin + tampered)).status_code == 401
remote.proxy.resume(ROOT, "replacement-gateway")
assert (await remote.client.get(remote.proxy.origin + local)).status_code == 401
+283
View File
@@ -0,0 +1,283 @@
"""Real loopback sockets and subprocess pipes; no external host or credentials."""
import asyncio
import contextlib
import socket
import sys
from unittest.mock import MagicMock
import pytest
from websockets.asyncio.client import connect
from websockets.asyncio.server import serve
from nanobot.webui import remote_ssh
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, open_tunnel
PROFILE = RemoteProfile(name="Fixture", host="fixture.test")
ECHO = "import os\nwhile data := os.read(0, 65536):\n os.write(1, data)\n"
def assert_owned(port):
with socket.socket() as competitor:
competitor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
with pytest.raises(OSError):
competitor.bind(("127.0.0.1", port))
competitor.listen()
@pytest.fixture
def ssh_child(monkeypatch):
real_spawn = asyncio.create_subprocess_exec
children = []
state = {"script": ECHO, "port": 0, "gate": None, "started": asyncio.Event()}
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
async def spawn(*args, **kwargs):
assert args[-3:] == ("-W", "127.0.0.1:8765", "fixture.test")
assert "-L" not in args
assert_owned(state["port"])
child = await real_spawn(sys.executable, "-u", "-c", state["script"], **kwargs)
children.append(child)
state["started"].set()
if state["gate"] is not None:
await state["gate"].wait()
return child
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
return state, children
async def test_large_binary_stream_and_half_close(ssh_child):
state, children = ssh_child
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
payload = bytes(range(256)) * 4096
async def upload():
writer.write(payload)
await writer.drain()
writer.write_eof()
try:
_, response = await asyncio.wait_for(asyncio.gather(upload(), reader.read()), 10)
assert response == payload
assert_owned(tunnel.port)
finally:
writer.close()
await writer.wait_closed()
await tunnel.close()
assert children and all(child.returncode is not None for child in children)
async def test_http_keepalive_and_chunked_upload(ssh_child):
import httpx
state, _ = ssh_child
state["script"] = """
import sys
stream = sys.stdin.buffer
while stream.readline():
headers = {}
while (line := stream.readline()) not in (b'\\r\\n', b''):
key, value = line.decode().split(':', 1)
headers[key.lower()] = value.strip()
if headers.get('transfer-encoding') == 'chunked':
body = b''
while size := int(stream.readline(), 16):
body += stream.read(size)
stream.read(2)
stream.read(2)
else:
body = stream.read(int(headers.get('content-length', '0')))
sys.stdout.buffer.write(b'HTTP/1.1 200 OK\\r\\nContent-Length: ' + str(len(body)).encode() + b'\\r\\n\\r\\n' + body)
sys.stdout.buffer.flush()
"""
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
async def chunks():
for _ in range(4):
yield b"chunk" * 10000
try:
async with httpx.AsyncClient(trust_env=False) as client:
base = f"http://127.0.0.1:{tunnel.port}"
response = await client.post(base, content=chunks())
assert response.content == b"chunk" * 40000
response = await client.post(base, content=b"keepalive")
assert response.content == b"keepalive"
finally:
await tunnel.close()
async def test_websocket_upgrade_and_bidirectional_messages(ssh_child):
state, _ = ssh_child
async def echo(websocket):
async for message in websocket:
await websocket.send(message)
async with serve(echo, "127.0.0.1", 0) as server:
port = server.sockets[0].getsockname()[1]
state["script"] = f"""
import os, socket, threading
upstream = socket.create_connection(('127.0.0.1', {port}))
def upload():
while data := os.read(0, 65536):
upstream.sendall(data)
upstream.shutdown(socket.SHUT_WR)
threading.Thread(target=upload, daemon=True).start()
while data := upstream.recv(65536):
os.write(1, data)
"""
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
try:
async with connect(f"ws://127.0.0.1:{tunnel.port}", proxy=None) as websocket:
for message in ["hello", bytes(range(256)) * 1000, "still connected"]:
await websocket.send(message)
assert await asyncio.wait_for(websocket.recv(), 5) == message
finally:
await tunnel.close()
async def test_pause_keeps_origin_reserved_and_resume_reuses_it(ssh_child, tmp_path):
state, children = ssh_child
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
try:
writer.write(b"first")
await writer.drain()
assert await asyncio.wait_for(reader.readexactly(5), 5) == b"first"
await tunnel.pause()
assert not tunnel.active
assert_owned(tunnel.port)
assert all(child.returncode is not None for child in children)
assert await reader.read() == b""
blocked_reader, blocked_writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
try:
assert await asyncio.wait_for(blocked_reader.read(), 2) == b""
assert len(children) == 1
finally:
blocked_writer.close()
await blocked_writer.wait_closed()
tunnel.resume(PROFILE, 8765, tmp_path / "missing-known-hosts")
resumed_reader, resumed_writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
try:
resumed_writer.write(b"second")
await resumed_writer.drain()
assert await asyncio.wait_for(resumed_reader.readexactly(6), 5) == b"second"
finally:
resumed_writer.close()
await resumed_writer.wait_closed()
finally:
writer.close()
await writer.wait_closed()
await tunnel.close()
assert all(child.returncode is not None for child in children)
async def test_failed_ssh_never_releases_origin_or_forwards_to_competitor(ssh_child):
state, children = ssh_child
state["script"] = "import sys\nsys.stderr.write('Permission denied\\n' + 'x' * 100000)\nsys.exit(255)"
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
try:
assert await asyncio.wait_for(reader.read(), 5) == b""
await asyncio.gather(*tunnel._streams)
assert tunnel.error == "ssh_auth_failed"
assert_owned(tunnel.port)
await tunnel.pause()
assert_owned(tunnel.port)
finally:
writer.close()
await writer.wait_closed()
await tunnel.close()
assert children[0].returncode == 255
async def test_cancellation_during_subprocess_creation_reaps_child(ssh_child):
state, children = ssh_child
state["gate"] = asyncio.Event()
tunnel = await open_tunnel(PROFILE, 8765)
state["port"] = tunnel.port
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
try:
await asyncio.wait_for(state["started"].wait(), 5)
paused = asyncio.create_task(tunnel.pause())
await asyncio.sleep(0)
assert not paused.done()
assert_owned(tunnel.port)
state["gate"].set()
await asyncio.wait_for(paused, 5)
assert children[0].returncode is not None
assert await reader.read() == b""
finally:
state["gate"].set()
writer.close()
await writer.wait_closed()
await tunnel.close()
async def test_cancellation_before_relay_starts_closes_client():
tunnel = remote_ssh.Tunnel([], 0)
tunnel.server = MagicMock(is_serving=lambda: True)
writer = MagicMock()
tunnel.accept(asyncio.StreamReader(), writer)
await tunnel.pause()
writer.close.assert_called()
assert not tunnel._streams
async def test_occupied_port_is_rejected_even_with_reuseaddr(monkeypatch):
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
with socket.socket() as owner:
owner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
owner.bind(("127.0.0.1", 0))
owner.listen()
with pytest.raises(RemoteError, match="local_port_in_use"):
await open_tunnel(PROFILE, 8765, local_port=owner.getsockname()[1])
def test_windows_listener_uses_exclusive_bind(monkeypatch):
listener = MagicMock()
listener.getsockname.return_value = ("127.0.0.1", 24000)
monkeypatch.setattr(remote_ssh.socket, "socket", lambda: listener)
monkeypatch.setattr(remote_ssh.socket, "SO_EXCLUSIVEADDRUSE", 123456, raising=False)
assert remote_ssh._listen(24000, set()) is listener
listener.setsockopt.assert_called_once_with(socket.SOL_SOCKET, 123456, 1)
listener.bind.assert_called_once_with(("127.0.0.1", 24000))
def test_new_origin_skips_retired_ports_without_releasing_them_early(monkeypatch):
retired, fresh = MagicMock(), MagicMock()
retired.getsockname.return_value = ("127.0.0.1", 24000)
fresh.getsockname.return_value = ("127.0.0.1", 24001)
def sockets():
yield retired
retired.close.assert_not_called()
yield fresh
candidates = sockets()
monkeypatch.setattr(remote_ssh.socket, "socket", lambda: next(candidates))
assert remote_ssh._listen(0, {24000}) is fresh
retired.close.assert_called_once()
fresh.close.assert_not_called()
async def test_listener_is_released_only_on_final_close(monkeypatch):
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
tunnel = await open_tunnel(PROFILE, 8765)
try:
assert_owned(tunnel.port)
await tunnel.pause()
assert_owned(tunnel.port)
finally:
await tunnel.close()
with contextlib.closing(socket.socket()) as replacement:
replacement.bind(("127.0.0.1", tunnel.port))
replacement.listen()
+4 -2
View File
@@ -75,7 +75,7 @@ def test_unresolvable_includes_and_invalid_lines_do_not_hide_other_hosts(ssh_hom
assert result["incomplete"]
@pytest.mark.parametrize("contents", [b"\xff", b"x" * 262145])
@pytest.mark.parametrize("contents", [b"\xff", b"x" * 262145], ids=["invalid-utf8", "oversized"])
def test_unreadable_or_oversized_custom_config_is_an_explicit_error(ssh_home, contents):
path = ssh_home / "config"
path.write_bytes(contents)
@@ -116,7 +116,7 @@ def test_invalid_paths_rejected_before_reading(path):
@pytest.mark.parametrize(("override", "expected"), [(None, "2222"), (2200, "2200")])
def test_system_ssh_inherits_config_port_user_and_identity(ssh_home, override, expected):
config = ssh_home / "config"
config.write_text("Host example-test\n HostName 192.0.2.10\n User tester\n Port 2222\n IdentityFile /tmp/test-key\n")
config.write_text("Host example-test\n HostName 192.0.2.10\n User tester\n Port 2222\n IdentityFile /tmp/test-key\n RemoteCommand tmux attach\n RequestTTY force\n")
profile = RemoteProfile(name="Test", host="example-test", ssh_config=str(config), port=override)
# This controlled fixture has no Match exec; -G makes no network connections.
result = subprocess.run([*ssh_arguments(profile), "-G", profile.host],
@@ -125,6 +125,8 @@ def test_system_ssh_inherits_config_port_user_and_identity(ssh_home, override, e
assert settings["port"] == expected
assert settings["user"] == "tester"
assert settings["identityfile"] == "/tmp/test-key"
assert settings.get("remotecommand", "none") == "none"
assert settings["requesttty"] == "false"
async def test_manager_discovery_does_not_save_profiles_or_connect(ssh_home):