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,91 @@
|
||||
"""An owned OpenSSH master, never a user's shared control socket."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class SSHMaster:
|
||||
"""One authenticated transport per pinned connection, reaped on pause."""
|
||||
|
||||
def __init__(self, args: list[str], host: str) -> None:
|
||||
self.args = args
|
||||
self.host = host
|
||||
self._directory: tempfile.TemporaryDirectory[str] | None = None
|
||||
self._process: asyncio.subprocess.Process | None = None
|
||||
self._stderr: asyncio.Task[None] | None = None
|
||||
self._error = bytearray()
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def arguments(self, channel: list[str]) -> list[str]:
|
||||
from nanobot.webui.remote_ssh import RemoteError, ssh_error
|
||||
|
||||
async with self._lock:
|
||||
if self._process is None or self._process.returncode is not None:
|
||||
await self.close()
|
||||
self._directory = tempfile.TemporaryDirectory(prefix="nb-ssh-")
|
||||
path = str(Path(self._directory.name) / "s")
|
||||
# Unix-domain socket paths have a small platform-dependent limit.
|
||||
if len(path.encode()) >= 100:
|
||||
await self.close()
|
||||
return channel
|
||||
self._error.clear()
|
||||
args = [self.args[0], "-o", "ControlMaster=yes", "-o", f"ControlPath={path}",
|
||||
"-o", "ControlPersist=no", *self.args[1:], "-N", self.host]
|
||||
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
|
||||
*args, stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
))
|
||||
try:
|
||||
self._process = await asyncio.shield(spawn)
|
||||
except asyncio.CancelledError:
|
||||
self._process = await spawn
|
||||
await self.close()
|
||||
raise
|
||||
except BaseException:
|
||||
await self.close()
|
||||
raise
|
||||
process = self._process
|
||||
assert process is not None
|
||||
|
||||
async def errors() -> None:
|
||||
assert process.stderr is not None
|
||||
while chunk := await process.stderr.read(4096):
|
||||
self._error.extend(chunk[:max(0, 8192 - len(self._error))])
|
||||
|
||||
self._stderr = asyncio.create_task(errors())
|
||||
try:
|
||||
async with asyncio.timeout(20):
|
||||
while not Path(path).exists():
|
||||
if process.returncode is not None:
|
||||
await self._stderr
|
||||
raise RemoteError(ssh_error(bytes(self._error)))
|
||||
await asyncio.sleep(0.02)
|
||||
except TimeoutError:
|
||||
await self.close()
|
||||
raise RemoteError("ssh_unreachable") from None
|
||||
except BaseException:
|
||||
await self.close()
|
||||
raise
|
||||
assert self._directory is not None
|
||||
# OpenSSH uses the first occurrence. Our private path overrides the
|
||||
# explicit no-sharing defaults, not host/agent/forwarding safeguards.
|
||||
return [channel[0], "-S", str(Path(self._directory.name) / "s"), *channel[1:]]
|
||||
|
||||
async def close(self) -> None:
|
||||
from nanobot.webui.remote_ssh import stop_process
|
||||
|
||||
if self._process is not None:
|
||||
await stop_process(self._process)
|
||||
self._process = None
|
||||
if self._stderr is not None:
|
||||
self._stderr.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await self._stderr
|
||||
self._stderr = None
|
||||
if self._directory is not None:
|
||||
self._directory.cleanup()
|
||||
self._directory = None
|
||||
@@ -23,8 +23,23 @@ from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write
|
||||
from nanobot.webui.remote_ssh import RemoteError
|
||||
|
||||
# No dynamic command, destination or environment input is accepted by the bridge.
|
||||
# SSH_ORIGINAL_COMMAND is deliberately ignored. Each invocation is one TCP stream.
|
||||
_BRIDGE = '''import os, socket, threading
|
||||
# SSH_ORIGINAL_COMMAND only negotiates the guard marker, never executed.
|
||||
# Each invocation is one TCP stream to the fixed loopback destination.
|
||||
_BRIDGE = '''import os, socket, threading, pathlib, sys, time
|
||||
# A multiplexed SSH transport authenticates only once. Re-check the exact
|
||||
# managed grant on EVERY new channel, including expiry and operator revocation.
|
||||
root = pathlib.Path(__file__).resolve().parent
|
||||
try:
|
||||
line = (root / "authorization").read_text()
|
||||
keys = root.parents[1] / "authorized_keys"
|
||||
valid = line.endswith(" nanobot-remote:" + root.name + "\\n") and line in keys.read_text().splitlines(keepends=True)
|
||||
except (OSError, ValueError):
|
||||
valid = False
|
||||
if not valid or time.time() >= UNTIL:
|
||||
sys.stderr.write("Permission denied: device authorization expired or revoked\\n")
|
||||
sys.exit(1)
|
||||
if os.environ.get("SSH_ORIGINAL_COMMAND") == "nanobot-remote-bridge-v2":
|
||||
os.write(1, b"NANOBOT_REMOTE_BRIDGE_2\\n")
|
||||
s = socket.create_connection(("127.0.0.1", PORT), timeout=10)
|
||||
s.settimeout(None)
|
||||
def send():
|
||||
@@ -50,6 +65,11 @@ finally:
|
||||
'''
|
||||
|
||||
|
||||
def bridge_source(port: int, until: int) -> str:
|
||||
"""Render only fixed, operator-approved destination and authorization expiry."""
|
||||
return _BRIDGE.replace("PORT", str(port)).replace("UNTIL", str(until))
|
||||
|
||||
|
||||
def metadata(config: Path) -> dict[str, Any]:
|
||||
"""Read only the WebUI credential out of the operator-selected config."""
|
||||
try:
|
||||
@@ -100,7 +120,7 @@ def write_authorization(home: Path, request: PairRequest, port: int, until: int)
|
||||
target.mkdir(mode=0o700)
|
||||
try:
|
||||
bridge = target / "bridge.py"
|
||||
private_write(bridge, _BRIDGE.replace("PORT", str(port)).encode())
|
||||
private_write(bridge, bridge_source(port, until).encode())
|
||||
command = shlex.join(["/usr/bin/python3", "-I", "-S", str(bridge)]).replace("\\", "\\\\").replace('"', '\\"')
|
||||
expiry = datetime.datetime.fromtimestamp(until, datetime.UTC).strftime("%Y%m%d%H%M%SZ")
|
||||
line = f'restrict,expiry-time="{expiry}",command="{command}" {request.ssh_key} nanobot-remote:{request.id}\n'
|
||||
|
||||
@@ -31,6 +31,7 @@ from nanobot.webui.remote_ssh import Tunnel, _listen # pyright: ignore[reportPr
|
||||
|
||||
_MAX_BYTES = 64 * 1024 * 1024
|
||||
_MAX_CAPABILITIES = 10000
|
||||
_STATIC_ASSET = re.compile(r"/assets/[^/]+-[A-Za-z0-9_-]{8,}\.(?:js|css|woff2?|ttf|svg|png|webp|ico)$")
|
||||
_MEDIA_PATH = r"/api/media/[A-Za-z0-9_-]{22}/[A-Za-z0-9_-]+"
|
||||
# Consume absolute URLs unchanged before matching gateway-relative media paths.
|
||||
# An external site's similarly named route is not this proxy's capability.
|
||||
@@ -307,6 +308,15 @@ class RemoteProxy:
|
||||
outgoing = {key: value for key, value in upstream.headers.items()
|
||||
if key.lower() in _RESPONSE_HEADERS}
|
||||
outgoing["Cache-Control"] = "no-store"
|
||||
upstream_cache = upstream.headers.get("cache-control", "").lower()
|
||||
if (upstream.status_code == 200 and _STATIC_ASSET.fullmatch(path)
|
||||
and not request.rel_url.query and "set-cookie" not in upstream.headers
|
||||
and "public" in upstream_cache and "immutable" in upstream_cache
|
||||
and "no-store" not in upstream_cache and "private" not in upstream_cache
|
||||
and "application/json" not in upstream.headers.get("content-type", "")):
|
||||
# Only versioned public build assets, never HTML, API data,
|
||||
# credentials or media capabilities. Keep caches browser-local.
|
||||
outgoing["Cache-Control"] = "private, max-age=31536000, immutable"
|
||||
if "application/json" in upstream.headers.get("content-type", ""):
|
||||
body = bytearray()
|
||||
async for chunk in upstream.aiter_bytes():
|
||||
|
||||
@@ -20,6 +20,10 @@ from typing import Any, cast
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
from nanobot.webui.remote_mux import SSHMaster
|
||||
|
||||
_BRIDGE_READY = b"NANOBOT_REMOTE_BRIDGE_2\n"
|
||||
|
||||
|
||||
class RemoteError(Exception):
|
||||
"""A stable, non-secret error code for the connection UI."""
|
||||
@@ -53,7 +57,7 @@ def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: P
|
||||
if isinstance(profile, PairedSSHProfile):
|
||||
# The server key's forced command owns the fixed destination. Do not
|
||||
# request forwarding or execute the ordinary credential probe.
|
||||
return [*args, profile.host, "nanobot-remote-bridge"]
|
||||
return [*args, profile.host, "nanobot-remote-bridge-v2"]
|
||||
return [*args, "-W", f"127.0.0.1:{remote_port}", profile.host]
|
||||
|
||||
|
||||
@@ -269,13 +273,26 @@ class Tunnel:
|
||||
self.enabled = True
|
||||
self.error = ""
|
||||
self._streams: set[asyncio.Task[None]] = set()
|
||||
self._master: SSHMaster | None = None
|
||||
self._master_args: tuple[list[str], str] | None = None
|
||||
self._paired = False
|
||||
self._reuse_verified = False
|
||||
self._probe_started = False
|
||||
# Leave room below OpenSSH's usual MaxSessions=10, including a live WS.
|
||||
self._slots = asyncio.Semaphore(8)
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self.enabled and self.server is not None and self.server.is_serving()
|
||||
|
||||
def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path) -> None:
|
||||
def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path | None) -> None:
|
||||
self.args = transport_arguments(profile, remote_port, known_hosts)
|
||||
self._paired = isinstance(profile, PairedSSHProfile)
|
||||
self._master_args = ((ssh_arguments(profile, known_hosts), profile.host)
|
||||
if os.name != "nt" and known_hosts and known_hosts.is_file() else None)
|
||||
self._master = SSHMaster(*self._master_args) if self._master_args else None
|
||||
self._reuse_verified = not self._paired
|
||||
self._probe_started = False
|
||||
self.error = ""
|
||||
self.enabled = True
|
||||
|
||||
@@ -294,9 +311,14 @@ class Tunnel:
|
||||
task.add_done_callback(finished)
|
||||
|
||||
async def _relay(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
async with self._slots:
|
||||
await self._stream(reader, writer)
|
||||
|
||||
async def _stream(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
process: asyncio.subprocess.Process | None = None
|
||||
pumps: list[asyncio.Task[None]] = []
|
||||
stderr = bytearray()
|
||||
master: SSHMaster | None = None
|
||||
|
||||
async def copy(source: asyncio.StreamReader, destination: asyncio.StreamWriter) -> None:
|
||||
while data := await source.read(65536):
|
||||
@@ -310,10 +332,16 @@ class Tunnel:
|
||||
stderr.extend(data[:max(0, 8192 - len(stderr))])
|
||||
|
||||
try:
|
||||
if self._master and (self._reuse_verified or not self._probe_started):
|
||||
# The first channel follows fresh SSH authentication. Only a
|
||||
# guarded bridge can authorize MORE channels on that transport.
|
||||
master = self._master
|
||||
self._probe_started = True
|
||||
args = await master.arguments(self.args) if master else self.args
|
||||
# Shield process creation so cancellation cannot lose a spawned child
|
||||
# before we have its handle and can reap it.
|
||||
spawn = asyncio.create_task(asyncio.create_subprocess_exec(
|
||||
*self.args, stdin=asyncio.subprocess.PIPE,
|
||||
*args, stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
|
||||
))
|
||||
try:
|
||||
@@ -323,8 +351,25 @@ class Tunnel:
|
||||
raise
|
||||
assert process is not None
|
||||
assert process.stdin is not None and process.stdout is not None and process.stderr is not None
|
||||
async def response() -> None:
|
||||
assert process is not None and process.stdout is not None
|
||||
if self._paired:
|
||||
first = await process.stdout.readline()
|
||||
if first == _BRIDGE_READY:
|
||||
# Only the guarded bridge advertises this capability.
|
||||
# Old bridges forward HTTP unchanged: keep authenticating
|
||||
# every stream until the server bridge is upgraded.
|
||||
self._reuse_verified = True
|
||||
if self._master_args and self._master is None:
|
||||
self._master = SSHMaster(*self._master_args)
|
||||
else:
|
||||
self._reuse_verified = False
|
||||
writer.write(first)
|
||||
await writer.drain()
|
||||
await copy(process.stdout, writer)
|
||||
|
||||
pumps = [asyncio.create_task(copy(reader, process.stdin)),
|
||||
asyncio.create_task(copy(process.stdout, writer)),
|
||||
asyncio.create_task(response()),
|
||||
asyncio.create_task(drain_errors(process.stderr))]
|
||||
done, _ = await asyncio.wait(pumps[:2], return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in done:
|
||||
@@ -338,7 +383,9 @@ class Tunnel:
|
||||
await pumps[2]
|
||||
if process.returncode:
|
||||
self.error = ssh_error(bytes(stderr))
|
||||
except (OSError, ConnectionError):
|
||||
except RemoteError as exc:
|
||||
self.error = str(exc)
|
||||
except (OSError, ConnectionError, ValueError):
|
||||
self.error = "ssh_unreachable"
|
||||
finally:
|
||||
for task in pumps:
|
||||
@@ -346,6 +393,10 @@ class Tunnel:
|
||||
await asyncio.gather(*pumps, return_exceptions=True)
|
||||
if process is not None:
|
||||
await stop_process(process)
|
||||
if master is not None and not self._reuse_verified:
|
||||
await master.close()
|
||||
if self._master is master:
|
||||
self._master = None
|
||||
writer.close()
|
||||
with contextlib.suppress(OSError):
|
||||
await writer.wait_closed()
|
||||
@@ -356,6 +407,9 @@ class Tunnel:
|
||||
for task in streams:
|
||||
task.cancel()
|
||||
await asyncio.gather(*streams, return_exceptions=True)
|
||||
if self._master is not None:
|
||||
await self._master.close()
|
||||
self._master = None
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pause()
|
||||
@@ -403,6 +457,7 @@ async def open_tunnel(
|
||||
listener = _listen(local_port, excluded_ports or set())
|
||||
tunnel = Tunnel(args, int(listener.getsockname()[1]))
|
||||
try:
|
||||
tunnel.resume(profile, remote_port, known_hosts)
|
||||
tunnel.server = await asyncio.start_server(tunnel.accept, sock=listener)
|
||||
return tunnel
|
||||
except BaseException:
|
||||
|
||||
Reference in new issue
Block a user