feat(webui): connect to existing remote nanobot instances (NAN-157)
This commit is contained in:
1 parent
6ecb74aea9
commit
11889c018e
34 files changed
+4074
-14
No files matched your search
@@ -676,6 +676,7 @@ class WebSocketChannel(BaseChannel):
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
self.gateway.http.remote_instances.resume()
|
||||
from nanobot.utils.logging_bridge import redirect_lib_logging
|
||||
|
||||
redirect_lib_logging("websockets", level="WARNING")
|
||||
@@ -880,6 +881,7 @@ class WebSocketChannel(BaseChannel):
|
||||
# -- Outbound WebSocket events -----------------------------------------
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self.gateway.http.remote_instances.close()
|
||||
server_task = self._server_task
|
||||
if (
|
||||
not self._running
|
||||
|
||||
@@ -45,6 +45,7 @@ def _channel() -> WebSocketChannel:
|
||||
gateway = MagicMock()
|
||||
gateway.session_manager = None
|
||||
gateway.http.settings_routes.close = AsyncMock()
|
||||
gateway.http.remote_instances.close = AsyncMock()
|
||||
return WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
MessageBus(),
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Local connection directory. Owns SSH tunnels, never remote gateway lifetimes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import secrets
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]
|
||||
from nanobot.webui import remote_ssh
|
||||
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
|
||||
|
||||
|
||||
class _SavedProfile(RemoteProfile):
|
||||
# Retain an origin per server so browser preferences/caches cannot drift
|
||||
# between servers on every reconnect. Not an editable API field.
|
||||
local_port: int = Field(default=0, ge=0, le=65535)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Connection:
|
||||
tunnel: Tunnel
|
||||
secret: str
|
||||
hostname: str
|
||||
config_path: str
|
||||
gateway_id: str
|
||||
error: str = ""
|
||||
|
||||
|
||||
class RemoteInstances:
|
||||
"""List/save/connect/disconnect with credentials confined to live connections."""
|
||||
|
||||
def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None:
|
||||
self.path = directory / "remote-instances.json"
|
||||
self.local_gateway_id = local_gateway_id
|
||||
self.connections: dict[str, Connection] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._unverified: dict[str, tuple[str, str, float]] = {}
|
||||
self._unknown_hosts: set[str] = set()
|
||||
self._closed = False
|
||||
|
||||
def _known_hosts(self, key: str) -> Path:
|
||||
return self.path.parent / "remote-hosts" / key
|
||||
|
||||
def resume(self) -> None:
|
||||
"""Allow a reused local channel to start again after its stop completed."""
|
||||
self._closed = False
|
||||
|
||||
def _read(self) -> dict[str, _SavedProfile]:
|
||||
if not self.path.exists():
|
||||
return {}
|
||||
try:
|
||||
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError
|
||||
return {str(uuid.UUID(key)): _SavedProfile.model_validate(value)
|
||||
for key, value in cast(dict[str, Any], raw).items()}
|
||||
except (ValueError, TypeError, OSError):
|
||||
raise RemoteError("profile_store_invalid") from None
|
||||
|
||||
def _write(self, profiles: dict[str, _SavedProfile]) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_write_text_atomic(self.path, json.dumps(
|
||||
{key: profile.model_dump() for key, profile in profiles.items()}, ensure_ascii=False,
|
||||
))
|
||||
self.path.chmod(0o600)
|
||||
|
||||
def snapshot(self) -> dict[str, Any]:
|
||||
return {"available": True, "machine_name": socket.gethostname(), "profiles": [
|
||||
{"id": key, **profile.model_dump(exclude={"local_port"}),
|
||||
"connected": key in self.connections
|
||||
and self.connections[key].tunnel.process.returncode is None
|
||||
and not self.connections[key].error}
|
||||
for key, profile in self._read().items()
|
||||
]}
|
||||
|
||||
async def health(self) -> dict[str, Any]:
|
||||
async def check(connection: Connection) -> None:
|
||||
if connection.tunnel.process.returncode is not None:
|
||||
connection.error = "ssh_unreachable"
|
||||
return
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=8, trust_env=False) as client:
|
||||
response = await client.get(
|
||||
f"http://127.0.0.1:{connection.tunnel.port}/webui/terminal",
|
||||
headers={"X-Nanobot-Auth": connection.secret},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
connection.error = "remote_unreachable"
|
||||
elif response.json().get("gatewayId") != connection.gateway_id:
|
||||
connection.error = "instance_changed"
|
||||
else:
|
||||
connection.error = ""
|
||||
except (httpx.HTTPError, ValueError, AttributeError):
|
||||
connection.error = "remote_unreachable"
|
||||
|
||||
await asyncio.gather(*(check(item) for item in tuple(self.connections.values())))
|
||||
return self.snapshot()
|
||||
|
||||
async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if action == "discover":
|
||||
from nanobot.webui.ssh_config import discover_hosts
|
||||
|
||||
config_file = payload.get("ssh_config", "")
|
||||
if not isinstance(config_file, str):
|
||||
raise RemoteError("invalid_profile")
|
||||
discovery = await asyncio.to_thread(discover_hosts, config_file)
|
||||
return dict(discovery)
|
||||
async with self._lock:
|
||||
if self._closed:
|
||||
raise RemoteError("local_io_error")
|
||||
profiles = self._read()
|
||||
key = str(payload.get("id", ""))
|
||||
if action == "save":
|
||||
profile = RemoteProfile.model_validate(payload.get("profile"))
|
||||
if key and key not in profiles:
|
||||
raise RemoteError("profile_not_found")
|
||||
if not key and len(profiles) >= 20:
|
||||
raise RemoteError("profile_limit")
|
||||
key = key or str(uuid.uuid4())
|
||||
if key in self.connections:
|
||||
raise RemoteError("disconnect_before_edit")
|
||||
target_changed = key in profiles and any(
|
||||
getattr(profiles[key], field) != getattr(profile, field)
|
||||
for field in ("host", "port", "ssh_config")
|
||||
)
|
||||
if target_changed:
|
||||
self._known_hosts(key).unlink(missing_ok=True)
|
||||
self._unverified.pop(key, None)
|
||||
self._unknown_hosts.discard(key)
|
||||
local_port = profiles[key].local_port if key in profiles and not target_changed else 0
|
||||
profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port)
|
||||
self._write(profiles)
|
||||
return {"id": key, **self.snapshot()}
|
||||
if key not in profiles:
|
||||
raise RemoteError("profile_not_found")
|
||||
if action == "connect":
|
||||
try:
|
||||
return await self._connect(key, profiles[key])
|
||||
except RemoteError as exc:
|
||||
if str(exc) == "host_key_unknown":
|
||||
self._unknown_hosts.add(key)
|
||||
else:
|
||||
self._unknown_hosts.discard(key)
|
||||
raise
|
||||
if action == "fingerprint":
|
||||
if key not in self._unknown_hosts or self._known_hosts(key).exists():
|
||||
raise RemoteError("host_key_changed")
|
||||
known_host, fingerprint = await remote_ssh.scan_host_key(profiles[key])
|
||||
challenge = secrets.token_urlsafe(24)
|
||||
self._unverified[key] = (challenge, known_host, time.monotonic() + 300)
|
||||
return {"fingerprint": fingerprint, "challenge": challenge}
|
||||
if action == "trust":
|
||||
pending = self._unverified.pop(key, None)
|
||||
if (not pending or pending[2] < time.monotonic()
|
||||
or not secrets.compare_digest(pending[0], str(payload.get("challenge", "")))
|
||||
or key not in self._unknown_hosts or self._known_hosts(key).exists()):
|
||||
raise RemoteError("host_key_changed")
|
||||
path = self._known_hosts(key)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_write_text_atomic(path, pending[1])
|
||||
path.chmod(0o600)
|
||||
self._unknown_hosts.discard(key)
|
||||
return {"trusted": True}
|
||||
if action in {"disconnect", "remove"}:
|
||||
connection = self.connections.pop(key, None)
|
||||
if connection:
|
||||
await connection.tunnel.close()
|
||||
if action == "remove":
|
||||
del profiles[key]
|
||||
self._write(profiles)
|
||||
self._known_hosts(key).unlink(missing_ok=True)
|
||||
self._unknown_hosts.discard(key)
|
||||
self._unverified.pop(key, None)
|
||||
return self.snapshot()
|
||||
raise RemoteError("unknown_action")
|
||||
|
||||
def _launch(self, key: str, profile: RemoteProfile, connection: Connection) -> dict[str, Any]:
|
||||
return {"id": key, "name": profile.name, "host": profile.host,
|
||||
"hostname": connection.hostname, "config_path": connection.config_path,
|
||||
"url": f"http://127.0.0.1:{connection.tunnel.port}/#/?bootstrapSecret={quote(connection.secret, safe='')}",
|
||||
"gateway_id": connection.gateway_id}
|
||||
|
||||
async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]:
|
||||
existing = self.connections.get(key)
|
||||
if existing:
|
||||
await self.health()
|
||||
if not existing.error:
|
||||
return self._launch(key, profile, existing)
|
||||
await existing.tunnel.close()
|
||||
del self.connections[key]
|
||||
if len(self.connections) >= 4:
|
||||
raise RemoteError("connection_limit")
|
||||
known_hosts = self._known_hosts(key)
|
||||
data = await remote_ssh.probe(profile, known_hosts)
|
||||
tunnel = await remote_ssh.open_tunnel(profile, data["port"], known_hosts, profile.local_port)
|
||||
base = f"http://127.0.0.1:{tunnel.port}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client:
|
||||
response = await client.get(
|
||||
f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]},
|
||||
)
|
||||
if response.status_code in {401, 403}:
|
||||
raise RemoteError("remote_auth_failed")
|
||||
if response.status_code != 200:
|
||||
raise RemoteError("incompatible_gateway")
|
||||
raw_identity = response.json()
|
||||
if not isinstance(raw_identity, dict):
|
||||
raise RemoteError("incompatible_gateway")
|
||||
identity = cast(dict[str, Any], raw_identity)
|
||||
if (identity.get("protocolVersion") != 1
|
||||
or not isinstance(identity.get("gatewayId"), str)):
|
||||
raise RemoteError("incompatible_gateway")
|
||||
if identity["gatewayId"] == self.local_gateway_id:
|
||||
raise RemoteError("same_instance")
|
||||
# Require the installed WebUI too, not just a port answering HTTP.
|
||||
page = await client.get(base + "/")
|
||||
if page.status_code != 200 or "text/html" not in page.headers.get("content-type", ""):
|
||||
raise RemoteError("webui_unavailable")
|
||||
connection = Connection(
|
||||
tunnel, data["secret"], str(data.get("hostname", profile.host)),
|
||||
str(data.get("config_path", profile.config_path)), identity["gatewayId"],
|
||||
)
|
||||
profiles = self._read()
|
||||
profiles[key].local_port = tunnel.port
|
||||
self._write(profiles)
|
||||
self.connections[key] = connection
|
||||
return self._launch(key, profile, connection)
|
||||
except BaseException as exc:
|
||||
await tunnel.close()
|
||||
if isinstance(exc, httpx.HTTPError):
|
||||
raise RemoteError("remote_unreachable") from None
|
||||
if isinstance(exc, ValueError):
|
||||
raise RemoteError("incompatible_gateway") from None
|
||||
raise
|
||||
|
||||
async def close(self) -> None:
|
||||
self._closed = True
|
||||
async with self._lock:
|
||||
connections, self.connections = self.connections, {}
|
||||
await asyncio.gather(*(item.tunnel.close() for item in connections.values()))
|
||||
@@ -0,0 +1,262 @@
|
||||
"""SSH-only access to an existing nanobot. Never installs or starts a remote process.
|
||||
|
||||
The system SSH client owns key/agent authentication and host verification. Probe
|
||||
output is private: only the WebUI credential is read, never provider credentials.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
import shutil
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class RemoteError(Exception):
|
||||
"""A stable, non-secret error code for the connection UI."""
|
||||
|
||||
|
||||
class RemoteProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
|
||||
name: str = Field(min_length=1, max_length=64)
|
||||
host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9._:@-]*$")
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
ssh_config: str = Field(default="", max_length=2048)
|
||||
identity_file: str = Field(default="", max_length=2048)
|
||||
config_path: str = Field(default="~/.nanobot/config.json", min_length=1, max_length=2048)
|
||||
runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$")
|
||||
|
||||
@field_validator("ssh_config", "identity_file", "config_path")
|
||||
@classmethod
|
||||
def safe_path(cls, value: str) -> str:
|
||||
if any(ord(char) < 32 for char in value):
|
||||
raise ValueError("control characters are not allowed")
|
||||
return value
|
||||
|
||||
|
||||
# Fixed program, quoted as one shell argument. No user-supplied shell commands.
|
||||
_PROBE = r'''
|
||||
import json, os, pathlib, socket, sys
|
||||
try:
|
||||
path = pathlib.Path(sys.argv[1]).expanduser()
|
||||
data = json.loads(path.read_text())
|
||||
ws = data.get("channels", {}).get("websocket", {})
|
||||
secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token")
|
||||
if not ws.get("enabled"):
|
||||
raise ValueError("webui_disabled")
|
||||
if not isinstance(secret, str) or not secret.strip() or "${" in secret:
|
||||
raise ValueError("webui_auth_required")
|
||||
if ws.get("publicWsUrl") or ws.get("public_ws_url"):
|
||||
raise ValueError("public_ws_unsupported")
|
||||
print(json.dumps({"port": ws.get("port", 8765), "secret": secret,
|
||||
"hostname": socket.gethostname(), "config_path": str(path)}))
|
||||
except FileNotFoundError:
|
||||
print(json.dumps({"error": "config_not_found"}))
|
||||
except PermissionError:
|
||||
print(json.dumps({"error": "config_permission"}))
|
||||
except ValueError as e:
|
||||
code = str(e)
|
||||
print(json.dumps({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported"} else "config_invalid"}))
|
||||
'''
|
||||
|
||||
|
||||
def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> list[str]:
|
||||
executable = shutil.which("ssh")
|
||||
if not executable:
|
||||
raise RemoteError("ssh_unavailable")
|
||||
args = [executable]
|
||||
for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]:
|
||||
if value:
|
||||
path = Path(value).expanduser()
|
||||
if not path.is_file():
|
||||
raise RemoteError("local_file_not_found")
|
||||
args.extend([flag, str(path)])
|
||||
# CLI options override config. Never forward the agent or reuse an unrelated
|
||||
# multiplexed session (whose identity/forwarding policy could be different).
|
||||
args.extend([
|
||||
"-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
|
||||
"-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "PermitLocalCommand=no",
|
||||
"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10",
|
||||
"-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2",
|
||||
"-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no",
|
||||
])
|
||||
if profile.port is not None:
|
||||
args.extend(["-p", str(profile.port)])
|
||||
if known_hosts and known_hosts.is_file():
|
||||
args.extend(["-o", f"UserKnownHostsFile={known_hosts}", "-o", "GlobalKnownHostsFile=none",
|
||||
"-o", "HostKeyAlias=nanobot-remote", "-o", "HostKeyAlgorithms=ssh-ed25519",
|
||||
"-o", "UpdateHostKeys=no"])
|
||||
return args
|
||||
|
||||
|
||||
def ssh_error(stderr: bytes) -> str:
|
||||
text = stderr.decode("utf-8", errors="replace").lower()
|
||||
if "host identification has changed" in text:
|
||||
return "host_key_changed"
|
||||
if "host key verification failed" in text or "no ed25519 host key is known" in text:
|
||||
return "host_key_unknown"
|
||||
if "permission denied" in text:
|
||||
return "ssh_auth_failed"
|
||||
if "sudo:" in text:
|
||||
return "runtime_user_denied"
|
||||
if "python3" in text and "not found" in text:
|
||||
return "python_unavailable"
|
||||
return "ssh_unreachable"
|
||||
|
||||
|
||||
async def stop_process(process: asyncio.subprocess.Process) -> None:
|
||||
if process.returncode is None:
|
||||
try:
|
||||
process.terminate()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
try:
|
||||
await asyncio.wait_for(process.wait(), 3)
|
||||
except TimeoutError:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
await process.wait()
|
||||
|
||||
|
||||
async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
|
||||
remote = ["python3", "-c", _PROBE, profile.config_path]
|
||||
if profile.runtime_user:
|
||||
remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote]
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*ssh_arguments(profile, known_hosts), profile.host, shlex.join(remote),
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(process.communicate(), 20)
|
||||
if process.returncode:
|
||||
raise RemoteError(ssh_error(stderr))
|
||||
try:
|
||||
raw = json.loads(stdout)
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError
|
||||
data = cast(dict[str, Any], raw)
|
||||
if data.get("error"):
|
||||
raise RemoteError(str(data["error"]))
|
||||
if not isinstance(data.get("secret"), str) or not data["secret"]:
|
||||
raise ValueError
|
||||
if type(data.get("port")) is not int or not 1 <= data["port"] <= 65535:
|
||||
raise ValueError
|
||||
return data
|
||||
except (ValueError, TypeError):
|
||||
raise RemoteError("config_invalid") from None
|
||||
except TimeoutError:
|
||||
raise RemoteError("ssh_unreachable") from None
|
||||
finally:
|
||||
await stop_process(process)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Tunnel:
|
||||
process: asyncio.subprocess.Process
|
||||
port: int
|
||||
|
||||
async def close(self) -> None:
|
||||
await stop_process(self.process)
|
||||
|
||||
|
||||
async def open_tunnel(
|
||||
profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None,
|
||||
local_port: int = 0,
|
||||
) -> Tunnel:
|
||||
# Reserve a loopback candidate. SSH remains responsible for binding and
|
||||
# ExitOnForwardFailure ensures a collision cannot connect us to another app.
|
||||
with socket.socket() as candidate:
|
||||
try:
|
||||
# Match OpenSSH's listener policy: a just-closed tunnel can leave
|
||||
# TIME_WAIT connections without another program owning the port.
|
||||
candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
candidate.bind(("127.0.0.1", local_port))
|
||||
candidate.listen(1)
|
||||
except OSError:
|
||||
raise RemoteError("local_port_in_use") from None
|
||||
port = int(candidate.getsockname()[1])
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*ssh_arguments(profile, known_hosts), "-N", "-L", f"127.0.0.1:{port}:127.0.0.1:{remote_port}",
|
||||
profile.host, stdin=asyncio.subprocess.DEVNULL,
|
||||
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
tunnel = Tunnel(process, port)
|
||||
try:
|
||||
for _ in range(100):
|
||||
if process.returncode is not None:
|
||||
stderr = await process.stderr.read() if process.stderr else b""
|
||||
raise RemoteError(ssh_error(stderr))
|
||||
try:
|
||||
reader, writer = await asyncio.wait_for(
|
||||
asyncio.open_connection("127.0.0.1", port), 0.2,
|
||||
)
|
||||
del reader
|
||||
writer.close()
|
||||
await writer.wait_closed()
|
||||
return tunnel
|
||||
except (OSError, TimeoutError):
|
||||
await asyncio.sleep(0.1)
|
||||
raise RemoteError("ssh_unreachable")
|
||||
except BaseException:
|
||||
await tunnel.close()
|
||||
raise
|
||||
|
||||
|
||||
async def scan_host_key(profile: RemoteProfile) -> tuple[str, str]:
|
||||
"""Return an UNVERIFIED key and fingerprint, never silently trust it.
|
||||
|
||||
Resolve SSH aliases with the user's own config. Scanning is deliberately
|
||||
direct; jump-host-only setups should verify via their existing SSH config.
|
||||
"""
|
||||
keyscan = shutil.which("ssh-keyscan")
|
||||
if not keyscan:
|
||||
raise RemoteError("ssh_unavailable")
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
*ssh_arguments(profile), "-G", profile.host,
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
output, _ = await asyncio.wait_for(process.communicate(), 10)
|
||||
if process.returncode:
|
||||
raise RemoteError("ssh_unreachable")
|
||||
finally:
|
||||
await stop_process(process)
|
||||
settings = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line)
|
||||
hostname, port = settings.get("hostname", ""), settings.get("port", "22")
|
||||
if not hostname or hostname.startswith("-") or not port.isdigit():
|
||||
raise RemoteError("invalid_profile")
|
||||
scan = await asyncio.create_subprocess_exec(
|
||||
keyscan, "-T", "5", "-p", port, "-t", "ed25519", hostname,
|
||||
stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
output, _ = await asyncio.wait_for(scan.communicate(), 8)
|
||||
for line in output.decode().splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) != 3 or fields[1] != "ssh-ed25519":
|
||||
continue
|
||||
try:
|
||||
binary = base64.b64decode(fields[2], validate=True)
|
||||
except ValueError:
|
||||
continue
|
||||
fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(binary).digest()).decode().rstrip("=")
|
||||
return f"nanobot-remote ssh-ed25519 {fields[2]}\n", fingerprint
|
||||
raise RemoteError("host_key_scan_failed")
|
||||
except TimeoutError:
|
||||
raise RemoteError("host_key_scan_failed") from None
|
||||
finally:
|
||||
await stop_process(scan)
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Discover named SSH targets without running SSH, shell hooks, or contacting hosts.
|
||||
|
||||
This is a bounded name index, not an SSH configuration evaluator. OpenSSH still
|
||||
resolves User, Port, IdentityFile, ProxyJump and Match at connection time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import stat
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from nanobot.webui.remote_ssh import RemoteError
|
||||
|
||||
|
||||
class SSHHost(TypedDict):
|
||||
host: str
|
||||
source: str
|
||||
ssh_config: str
|
||||
|
||||
|
||||
class SSHDiscovery(TypedDict):
|
||||
hosts: list[SSHHost]
|
||||
files: list[str]
|
||||
incomplete: bool
|
||||
|
||||
|
||||
def discover_hosts(config_file: str = "") -> SSHDiscovery:
|
||||
"""Read literal Host names, including Include files, with no side effects.
|
||||
|
||||
Wildcard/negated Host patterns are not destinations. Conditional includes
|
||||
may contribute suggestions; those are not claims that a host is reachable.
|
||||
Only names and source paths are returned, never arbitrary config contents.
|
||||
"""
|
||||
if len(config_file) > 2048 or any(ord(char) < 32 for char in config_file):
|
||||
raise RemoteError("invalid_profile")
|
||||
home = Path.home()
|
||||
user_ssh = home / ".ssh"
|
||||
system_ssh = (Path(os.environ.get("PROGRAMDATA", "C:/ProgramData")) / "ssh"
|
||||
if os.name == "nt" else Path("/etc/ssh"))
|
||||
roots = [(Path(config_file).expanduser(), user_ssh)] if config_file else [
|
||||
(user_ssh / "config", user_ssh), (system_ssh / "ssh_config", system_ssh),
|
||||
]
|
||||
result: SSHDiscovery = {"hosts": [], "files": [], "incomplete": False}
|
||||
visited: set[Path] = set()
|
||||
names: set[str] = set()
|
||||
bytes_read = 0
|
||||
|
||||
def visit(path: Path, base: Path, *, required: bool = False) -> None:
|
||||
nonlocal bytes_read
|
||||
try:
|
||||
path = path.resolve()
|
||||
if path in visited:
|
||||
return
|
||||
if len(visited) >= 64 or bytes_read >= 1_048_576:
|
||||
result["incomplete"] = True
|
||||
return
|
||||
visited.add(path)
|
||||
info = path.stat()
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_size > 262_144:
|
||||
raise ValueError
|
||||
# Bound reads too, even if the file grows after stat().
|
||||
with path.open("rb") as stream:
|
||||
content = stream.read(min(262_145, 1_048_577 - bytes_read))
|
||||
bytes_read += len(content)
|
||||
if len(content) > 262_144 or bytes_read > 1_048_576:
|
||||
raise ValueError
|
||||
lines = content.decode("utf-8").splitlines()
|
||||
except FileNotFoundError:
|
||||
if required:
|
||||
raise RemoteError("local_file_not_found") from None
|
||||
return
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
if required:
|
||||
raise RemoteError("ssh_config_unreadable") from None
|
||||
result["incomplete"] = True
|
||||
return
|
||||
result["files"].append(str(path))
|
||||
for line in lines:
|
||||
match = re.match(r"^\s*(Host|Include)(?:\s*=\s*|\s+)(.*)$", line, re.I)
|
||||
if not match:
|
||||
continue
|
||||
try:
|
||||
values = shlex.split(match[2], comments=True)
|
||||
except ValueError:
|
||||
result["incomplete"] = True
|
||||
continue
|
||||
if match[1].lower() == "host":
|
||||
for name in values:
|
||||
if (len(name) > 253 or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._:@-]*", name)
|
||||
or name.casefold() in names):
|
||||
continue
|
||||
if len(result["hosts"]) >= 200:
|
||||
result["incomplete"] = True
|
||||
return
|
||||
names.add(name.casefold())
|
||||
result["hosts"].append({"host": name, "source": str(path),
|
||||
"ssh_config": str(roots[0][0].expanduser()) if config_file else ""})
|
||||
else:
|
||||
for pattern in values:
|
||||
# Tokens/environment-dependent paths cannot be resolved without
|
||||
# a target. Leave them to SSH; never invoke `ssh -G` on page load
|
||||
# because Match exec can execute arbitrary local commands.
|
||||
if "$" in pattern or "%" in pattern:
|
||||
result["incomplete"] = True
|
||||
continue
|
||||
expanded = Path(pattern).expanduser()
|
||||
if not expanded.is_absolute():
|
||||
expanded = base / expanded
|
||||
matches = glob.iglob(str(expanded))
|
||||
paths: list[str] = []
|
||||
for candidate in matches:
|
||||
if len(paths) >= 64:
|
||||
result["incomplete"] = True
|
||||
break
|
||||
paths.append(candidate)
|
||||
for candidate in sorted(paths):
|
||||
visit(Path(candidate), base)
|
||||
|
||||
for root, base in roots:
|
||||
visit(root, base, required=bool(config_file))
|
||||
return result
|
||||
@@ -164,6 +164,13 @@ class _WebUIThreadDiagnostics:
|
||||
event_loop_lag_ms: float = 0.0
|
||||
|
||||
_WEBUI_MUTATION_PATHS = {
|
||||
"remote.discover": "/api/remote-instances/discover",
|
||||
"remote.save": "/api/remote-instances/save",
|
||||
"remote.connect": "/api/remote-instances/connect",
|
||||
"remote.disconnect": "/api/remote-instances/disconnect",
|
||||
"remote.remove": "/api/remote-instances/remove",
|
||||
"remote.fingerprint": "/api/remote-instances/fingerprint",
|
||||
"remote.trust": "/api/remote-instances/trust",
|
||||
"automation.enable": "/api/webui/automations/enable",
|
||||
"automation.disable": "/api/webui/automations/disable",
|
||||
"automation.delete": "/api/webui/automations/delete",
|
||||
@@ -372,6 +379,11 @@ class GatewayHTTPHandler:
|
||||
self.ingress = ingress
|
||||
self.workspaces = workspaces
|
||||
self.settings = settings
|
||||
from nanobot.webui.remote_instances import RemoteInstances
|
||||
|
||||
self.remote_instances = RemoteInstances(
|
||||
settings.config.path.parent / "webui", local_gateway_id=tokens.instance_id,
|
||||
)
|
||||
self.skills_workspace_path = skills_workspace_path
|
||||
self.disabled_skills: set[str] = (
|
||||
disabled_skills if disabled_skills is not None else set()
|
||||
@@ -512,6 +524,8 @@ class GatewayHTTPHandler:
|
||||
return _http_error(404, "WebUI mutation action not found")
|
||||
|
||||
def _is_webui_mutation_path(self, path: str) -> bool:
|
||||
if path.startswith("/api/remote-instances/"):
|
||||
return True
|
||||
if self.settings_routes.is_mutation_path(path):
|
||||
return True
|
||||
if re.match(r"^/api/sessions/[^/]+/delete$", path):
|
||||
@@ -560,6 +574,8 @@ class GatewayHTTPHandler:
|
||||
request: WsRequest,
|
||||
got: str,
|
||||
) -> Any | None:
|
||||
if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"):
|
||||
return await self._dispatch_remote_instances(connection, request, got)
|
||||
# Token issue endpoint
|
||||
if self.config.token_issue_path:
|
||||
issue_expected = _normalize_config_path(self.config.token_issue_path)
|
||||
@@ -617,6 +633,38 @@ class GatewayHTTPHandler:
|
||||
|
||||
return connection.respond(404, "Not Found")
|
||||
|
||||
async def _dispatch_remote_instances(
|
||||
self, connection: Any, request: WsRequest, path: str,
|
||||
) -> Response:
|
||||
from pydantic import ValidationError
|
||||
|
||||
from nanobot.webui.remote_ssh import RemoteError
|
||||
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
# A public/reverse-proxied WebUI must never gain access to this machine's
|
||||
# SSH agent, private keys or network. Same checks as local folder picking.
|
||||
if not (_is_loopback_host(self.config.host)
|
||||
and _is_local_browser_request(connection, request.headers)):
|
||||
return _http_error(403, "remote_connections_local_only")
|
||||
origin = request.headers.get("Origin", "")
|
||||
if origin and not _is_loopback_host(urlsplit(origin).hostname or ""):
|
||||
return _http_error(403, "remote_connections_local_only")
|
||||
try:
|
||||
if path == "/api/remote-instances":
|
||||
return _http_json_response(await self.remote_instances.health(), extra_headers=_NO_STORE_HEADERS)
|
||||
if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
|
||||
return _http_error(405, "WebSocket required")
|
||||
payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, {})
|
||||
result = await self.remote_instances.action(path.rsplit("/", 1)[-1], payload)
|
||||
return _http_json_response(result, extra_headers=_NO_STORE_HEADERS)
|
||||
except RemoteError as exc:
|
||||
return _http_error(400, str(exc))
|
||||
except ValidationError:
|
||||
return _http_error(400, "invalid_profile")
|
||||
except OSError:
|
||||
return _http_error(500, "local_io_error")
|
||||
|
||||
def _log_slow_http(self, path: str, response: Any | None, started: float) -> None:
|
||||
elapsed_ms = int((time.perf_counter() - started) * 1000)
|
||||
if elapsed_ms < _SLOW_WEBUI_HTTP_LOG_MS:
|
||||
|
||||
Reference in new issue
Block a user