perf(remote): reuse guarded SSH transports and cache static assets
This commit is contained in:
1 parent
719a5c3fcf
commit
4fd4dc522d
8 files changed
+441
-15
No files matched your search
@@ -0,0 +1,179 @@
|
||||
"""Private SSH master lifetime and guarded-bridge compatibility."""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.webui import remote_mux, remote_ssh
|
||||
from nanobot.webui.remote_mux import SSHMaster
|
||||
from nanobot.webui.remote_ssh import PairedSSHProfile, RemoteError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def master_child(monkeypatch):
|
||||
real_spawn = asyncio.create_subprocess_exec
|
||||
children, commands = [], []
|
||||
state = {"fail": False, "gate": None, "started": asyncio.Event()}
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
commands.append(args)
|
||||
path = next(arg.split("=", 1)[1] for arg in args if arg.startswith("ControlPath="))
|
||||
script = ("import sys;sys.stderr.write('Permission denied');sys.exit(255)" if state["fail"] else
|
||||
"import socket,sys,time;s=socket.socket(socket.AF_UNIX);s.bind(sys.argv[1]);s.listen();time.sleep(120)")
|
||||
child = await real_spawn(sys.executable, "-u", "-c", script, path, **kwargs)
|
||||
children.append(child)
|
||||
state["started"].set()
|
||||
if state["gate"] is not None:
|
||||
await state["gate"].wait()
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(remote_mux.asyncio, "create_subprocess_exec", spawn)
|
||||
return state, children, commands
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
|
||||
async def test_parallel_channels_share_only_owned_master_and_close_cleans_it(master_child):
|
||||
_, children, commands = master_child
|
||||
master = SSHMaster(["ssh", "-o", "ControlMaster=no", "-o", "ControlPath=none"], "pinned-host")
|
||||
channel = ["ssh", "-o", "ControlPath=none", "-W", "127.0.0.1:8765", "pinned-host"]
|
||||
paths = []
|
||||
try:
|
||||
results = await asyncio.gather(*(master.arguments(channel) for _ in range(8)))
|
||||
assert len(children) == 1
|
||||
paths = [Path(result[2]) for result in results]
|
||||
assert len(set(paths)) == 1 and paths[0].exists()
|
||||
assert paths[0].parent.stat().st_mode & 0o777 == 0o700
|
||||
assert commands[0][-2:] == ("-N", "pinned-host")
|
||||
assert "ControlPersist=no" in commands[0]
|
||||
assert all(result[3:] == channel[1:] for result in results)
|
||||
await master.close()
|
||||
assert children[0].returncode is not None
|
||||
assert not paths[0].parent.exists()
|
||||
renewed = await master.arguments(channel)
|
||||
assert renewed[2] != str(paths[0]) and len(children) == 2
|
||||
finally:
|
||||
await master.close()
|
||||
assert all(child.returncode is not None for child in children)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
|
||||
async def test_dead_master_reauthenticates_and_does_not_share_other_connections(master_child):
|
||||
_, children, _ = master_child
|
||||
first = SSHMaster(["ssh"], "host")
|
||||
second = SSHMaster(["ssh"], "host")
|
||||
channel = ["ssh", "host", "bridge"]
|
||||
try:
|
||||
original = await first.arguments(channel)
|
||||
isolated = await second.arguments(channel)
|
||||
assert original[2] != isolated[2]
|
||||
children[0].terminate()
|
||||
await children[0].wait()
|
||||
renewed = await first.arguments(channel)
|
||||
assert len(children) == 3
|
||||
assert renewed[2] not in (original[2], isolated[2])
|
||||
assert not Path(original[2]).parent.exists()
|
||||
assert children[1].returncode is None
|
||||
assert await second.arguments(channel) == isolated
|
||||
finally:
|
||||
await first.close()
|
||||
await second.close()
|
||||
assert all(child.returncode is not None for child in children)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
|
||||
async def test_long_socket_path_falls_back_without_starting_a_master(tmp_path, monkeypatch, master_child):
|
||||
_, children, _ = master_child
|
||||
directory = tmp_path / ("long-" * 25)
|
||||
directory.mkdir()
|
||||
monkeypatch.setattr(remote_mux.tempfile, "tempdir", str(directory))
|
||||
master = SSHMaster(["ssh"], "host")
|
||||
channel = ["ssh", "host", "bridge"]
|
||||
assert await master.arguments(channel) == channel
|
||||
assert master._directory is None
|
||||
assert children == []
|
||||
assert list(directory.iterdir()) == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
|
||||
async def test_failed_authentication_is_not_hidden_by_fallback(master_child):
|
||||
state, children, _ = master_child
|
||||
state["fail"] = True
|
||||
master = SSHMaster(["ssh"], "host")
|
||||
with pytest.raises(RemoteError, match="ssh_auth_failed"):
|
||||
await master.arguments(["ssh", "host", "bridge"])
|
||||
assert master._directory is None
|
||||
assert children[0].returncode == 255
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="OpenSSH control sockets require Unix")
|
||||
async def test_cancel_during_master_spawn_reaps_process_and_socket(master_child):
|
||||
state, children, _ = master_child
|
||||
state["gate"] = asyncio.Event()
|
||||
master = SSHMaster(["ssh"], "host")
|
||||
task = asyncio.create_task(master.arguments(["ssh", "host", "bridge"]))
|
||||
await state["started"].wait()
|
||||
task.cancel()
|
||||
state["gate"].set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert master._directory is None
|
||||
assert all(child.returncode is not None for child in children)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("guarded", [False, True])
|
||||
@pytest.mark.parametrize("loses_guard", [False, True])
|
||||
async def test_paired_tunnel_reuses_only_after_guarded_bridge_marker(tmp_path, monkeypatch, guarded, loses_guard):
|
||||
real_spawn = asyncio.create_subprocess_exec
|
||||
known = tmp_path / "known_hosts"
|
||||
known.write_text("pinned fixture")
|
||||
masters = []
|
||||
|
||||
class Master:
|
||||
def __init__(self, *args):
|
||||
self.arguments = AsyncMock(side_effect=lambda channel: channel)
|
||||
self.close = AsyncMock()
|
||||
masters.append(self)
|
||||
|
||||
monkeypatch.setattr(remote_ssh, "SSHMaster", Master)
|
||||
monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")
|
||||
children = []
|
||||
script = (f"import os\nos.write(1, {remote_ssh._BRIDGE_READY!r})\n" if guarded else "import os\n")
|
||||
script += "while data := os.read(0,65536):\n os.write(1,data)\n"
|
||||
|
||||
async def spawn(*args, **kwargs):
|
||||
source = script
|
||||
if loses_guard and len(children) >= 1:
|
||||
source = "import os\nwhile data := os.read(0,65536):\n os.write(1,data)\n"
|
||||
child = await real_spawn(sys.executable, "-u", "-c", source, **kwargs)
|
||||
children.append(child)
|
||||
return child
|
||||
|
||||
monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
|
||||
profile = PairedSSHProfile(name="Fixture", host="fixture.test")
|
||||
tunnel = await remote_ssh.open_tunnel(profile, 8765, known)
|
||||
try:
|
||||
for _ in range(3):
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)
|
||||
writer.write(b"HTTP/1.1 200 OK\r\nbody")
|
||||
await writer.drain()
|
||||
writer.write_eof()
|
||||
assert await asyncio.wait_for(reader.read(), 5) == b"HTTP/1.1 200 OK\r\nbody"
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
if guarded and os.name != "nt":
|
||||
assert len(masters) == 1
|
||||
assert masters[0].arguments.await_count == (2 if loses_guard else 3)
|
||||
elif os.name != "nt":
|
||||
assert len(masters) == 1
|
||||
assert masters[0].arguments.await_count == 1
|
||||
else:
|
||||
assert masters == []
|
||||
finally:
|
||||
await tunnel.close()
|
||||
assert all(child.returncode is not None for child in children)
|
||||
if masters:
|
||||
masters[0].close.assert_awaited_once()
|
||||
@@ -176,11 +176,12 @@ def test_paired_transport_cannot_fall_back_to_generic_probe_or_forwarding(pair,
|
||||
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 transport[-1] == "nanobot-remote-bridge-v2"
|
||||
assert "sudo" not in " ".join(transport)
|
||||
|
||||
|
||||
def test_fixed_bridge_streams_only_to_baked_in_loopback_port():
|
||||
@pytest.mark.parametrize("command", ["echo MUST-NOT-EXECUTE", "nanobot-remote-bridge-v2"])
|
||||
def test_fixed_bridge_streams_only_to_baked_in_loopback_port(tmp_path, command):
|
||||
# Real bidirectional bytes, no SSH_ORIGINAL_COMMAND interpolation.
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
@@ -196,12 +197,39 @@ def test_fixed_bridge_streams_only_to_baked_in_loopback_port():
|
||||
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))],
|
||||
target = tmp_path / ".ssh" / "nanobot-remote" / "device"
|
||||
target.mkdir(parents=True)
|
||||
line = "restrict fixture-key nanobot-remote:device\n"
|
||||
(target / "authorization").write_text(line)
|
||||
(tmp_path / ".ssh" / "authorized_keys").write_text(line)
|
||||
bridge = target / "bridge.py"
|
||||
bridge.write_text(remote_pair_server.bridge_source(port, int(time.time()) + 60))
|
||||
result = subprocess.run([sys.executable, "-I", "-S", str(bridge)],
|
||||
input=b"hello-webui", capture_output=True, timeout=5,
|
||||
env={**os.environ, "SSH_ORIGINAL_COMMAND": "echo MUST-NOT-EXECUTE"})
|
||||
env={**os.environ, "SSH_ORIGINAL_COMMAND": command})
|
||||
worker.join(2)
|
||||
assert result.returncode == 0
|
||||
assert result.stdout == b"received:hello-webui"
|
||||
prefix = remote_ssh._BRIDGE_READY if command == "nanobot-remote-bridge-v2" else b""
|
||||
assert result.stdout == prefix + b"received:hello-webui"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reason", ["expired", "revoked", "missing", "another-device"])
|
||||
def test_guarded_bridge_rejects_new_channels_without_connecting(tmp_path, reason):
|
||||
target = tmp_path / ".ssh" / "nanobot-remote" / "device"
|
||||
target.mkdir(parents=True)
|
||||
line = "restrict fixture-key nanobot-remote:device\n"
|
||||
(target / "authorization").write_text(line)
|
||||
keys = tmp_path / ".ssh" / "authorized_keys"
|
||||
keys.write_text(line if reason == "expired" else line.replace(":device", ":other") if reason == "another-device" else "")
|
||||
if reason == "missing":
|
||||
keys.unlink()
|
||||
bridge = target / "bridge.py"
|
||||
bridge.write_text(remote_pair_server.bridge_source(1, int(time.time()) + (-1 if reason == "expired" else 60)))
|
||||
result = subprocess.run([sys.executable, "-I", "-S", str(bridge)], capture_output=True, timeout=5,
|
||||
env={**os.environ, "SSH_ORIGINAL_COMMAND": "nanobot-remote-bridge-v2"})
|
||||
assert result.returncode == 1
|
||||
assert not result.stdout # No reuse capability or connection to the target.
|
||||
assert b"Permission denied" in result.stderr
|
||||
|
||||
|
||||
async def test_api_pair_finalization_pins_host_and_hides_credentials(tmp_path):
|
||||
|
||||
@@ -44,6 +44,15 @@ async def remote(tmp_path, monkeypatch):
|
||||
async def process(connection, request):
|
||||
seen.append(request)
|
||||
path = urlsplit(request.path).path
|
||||
if path.startswith("/assets/"):
|
||||
response = connection.respond(200, "fixture asset")
|
||||
response.headers["Content-Type"] = "application/javascript"
|
||||
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
if "private" in request.path:
|
||||
response.headers["Cache-Control"] = "private, no-store"
|
||||
if "cookie" in request.path:
|
||||
response.headers["Set-Cookie"] = "session=private"
|
||||
return response
|
||||
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
|
||||
@@ -118,6 +127,19 @@ async def bootstrap(remote, headers=None):
|
||||
return response.json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path,cacheable", [
|
||||
("/assets/index-AbcD1234.js", True), ("/assets/index-AbcD1234.css", True),
|
||||
("/assets/private-AbcD1234.js", False), ("/assets/cookie-AbcD1234.js", False),
|
||||
("/assets/index-AbcD1234.js?token=secret", False), ("/assets/config.json", False),
|
||||
("/assets/index.js", False), ("/assets/index-AbcD1234.html", False),
|
||||
])
|
||||
async def test_cache_only_versioned_public_build_assets(remote, path, cacheable):
|
||||
response = await remote.client.get(remote.proxy.origin + path)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == ("private, max-age=31536000, immutable" if cacheable else "no-store")
|
||||
assert "set-cookie" not in response.headers
|
||||
|
||||
|
||||
async def test_remote_credentials_never_leave_the_backend(remote):
|
||||
first, second = await asyncio.gather(bootstrap(remote), bootstrap(remote))
|
||||
assert first["token"] != second["token"]
|
||||
|
||||
Reference in new issue
Block a user