From 192ca6e49e9194949041b310defe4699228d7c43 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Wed, 30 Sep 2026 15:09:14 +0800 Subject: [PATCH] feat(webui): complete remote pairing and connection recovery --- docs/guides/remote-instances.md | 250 ++++++- nanobot/cli/commands.py | 5 + nanobot/cli/remote.py | 139 ++++ nanobot/webui/native_folder_picker.py | 46 +- nanobot/webui/remote_discovery.py | 133 ++++ nanobot/webui/remote_instances.py | 309 ++++++-- nanobot/webui/remote_pair_server.py | 213 ++++++ nanobot/webui/remote_pairing.py | 322 +++++++++ nanobot/webui/remote_proxy.py | 368 ++++++++++ nanobot/webui/remote_ssh.py | 303 ++++++-- nanobot/webui/ws_http.py | 7 + pyproject.toml | 2 + tests/cli/test_remote_pair_defaults.py | 35 + tests/utils/test_native_folder_picker.py | 48 ++ tests/webui/test_gateway_webui_smoke.py | 54 ++ tests/webui/test_remote_discovery.py | 144 ++++ tests/webui/test_remote_instances.py | 475 ++++++++++++- tests/webui/test_remote_pairing.py | 297 ++++++++ tests/webui/test_remote_proxy.py | 387 ++++++++++ tests/webui/test_remote_tunnel.py | 283 ++++++++ tests/webui/test_ssh_config.py | 6 +- webui/src/App.tsx | 14 +- webui/src/components/Sidebar.tsx | 16 +- webui/src/components/remote/HostSwitcher.tsx | 106 ++- .../components/remote/PairRouteSettings.tsx | 58 ++ .../src/components/remote/QuickPairSetup.tsx | 210 ++++++ .../remote/RemoteConnectionsPage.tsx | 450 ++++++++---- .../src/components/remote/RemoteInstances.tsx | 41 +- webui/src/components/remote/SSHHostPicker.tsx | 134 ++-- .../src/components/remote/useHostSessions.ts | 106 ++- webui/src/i18n/locales/en/common.json | 139 +++- webui/src/i18n/locales/es/common.json | 139 +++- webui/src/i18n/locales/fr/common.json | 139 +++- webui/src/i18n/locales/id/common.json | 139 +++- webui/src/i18n/locales/ja/common.json | 139 +++- webui/src/i18n/locales/ko/common.json | 139 +++- webui/src/i18n/locales/pt-BR/common.json | 139 +++- webui/src/i18n/locales/vi/common.json | 139 +++- webui/src/i18n/locales/zh-CN/common.json | 139 +++- webui/src/i18n/locales/zh-TW/common.json | 139 +++- webui/src/lib/remote-instances.ts | 43 +- webui/src/lib/remote-pair-return.ts | 51 ++ webui/src/lib/ssh-address.ts | 60 ++ webui/src/main.tsx | 3 + webui/src/tests/app-layout.test.tsx | 84 ++- webui/src/tests/host-sessions.test.tsx | 74 +- webui/src/tests/host-switcher.test.tsx | 253 +++++++ webui/src/tests/pair-route.test.tsx | 78 +++ webui/src/tests/quick-pair.test.tsx | 263 +++++++ webui/src/tests/remote-instances.test.tsx | 661 ++++++++++++++++-- webui/src/tests/remote-pair-return.test.ts | 37 + webui/src/tests/ssh-address.test.ts | 30 + 52 files changed, 7313 insertions(+), 675 deletions(-) create mode 100644 nanobot/cli/remote.py create mode 100644 nanobot/webui/remote_discovery.py create mode 100644 nanobot/webui/remote_pair_server.py create mode 100644 nanobot/webui/remote_pairing.py create mode 100644 nanobot/webui/remote_proxy.py create mode 100644 tests/cli/test_remote_pair_defaults.py create mode 100644 tests/webui/test_remote_discovery.py create mode 100644 tests/webui/test_remote_pairing.py create mode 100644 tests/webui/test_remote_proxy.py create mode 100644 tests/webui/test_remote_tunnel.py create mode 100644 webui/src/components/remote/PairRouteSettings.tsx create mode 100644 webui/src/components/remote/QuickPairSetup.tsx create mode 100644 webui/src/lib/remote-pair-return.ts create mode 100644 webui/src/lib/ssh-address.ts create mode 100644 webui/src/tests/host-switcher.test.tsx create mode 100644 webui/src/tests/pair-route.test.tsx create mode 100644 webui/src/tests/quick-pair.test.tsx create mode 100644 webui/src/tests/remote-pair-return.test.ts create mode 100644 webui/src/tests/ssh-address.test.ts diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md index 9c4b8d6a3..03ca065b8 100644 --- a/docs/guides/remote-instances.md +++ b/docs/guides/remote-instances.md @@ -1,27 +1,160 @@ # Connect to an existing remote nanobot -Open your local **nanobot WebUI** and choose **Remote connections** in the sidebar -(below Channels). Setup opens in the main content area, with the sidebar still -available. Choose a host from **From your SSH config**, or enter an SSH address -such as `ubuntu@your-server` using **Connect to remote nanobot…**. -Give it a recognizable name, then choose **Save & connect**. Next time, select -the saved server. No port-forwarding command or `.command` launcher is needed. +Open your local **nanobot WebUI**, click the current host (initially **Local**) +at the bottom of the sidebar, and choose **Manage connections…**. This is the +single entry point for switching and managing hosts. The page lists this computer +and your saved servers. Choose +**Add server** to copy a prepared pairing command, or choose **Other ways → Use existing SSH settings** +to enter an SSH address such as +`ubuntu@your-server` or pick a suggested host from your SSH config. Choose +**Connect**. Next time, select the saved server directly. No port-forwarding +command or `.command` launcher is needed. -To add another server, choose **Connect to remote nanobot…** below your saved -connections. Use a server's menu to edit or forget it. The page supports browser -back/forward and the `#/remote` route. Leaving setup while SSH is connecting won't -switch you away from the page you chose when that connection finishes. +With more than five saved servers, the host menu includes search by name or SSH +address. The current server and recently used servers appear first; the local +computer stays at the top. Only the host list scrolls, so **Manage connections…** +stays visible. Use the arrow keys to choose a result, Enter to connect, and Escape +to close. Recent choices are remembered in this browser, not synced to servers. + +To add another server, choose **Add server** below your saved connections. Use a +server's menu to edit or forget it. Editing opens the same dialog; **Save changes** +saves without connecting or switching hosts. Disconnect an open server before +editing its connection settings. The page supports browser back/forward and the +`#/remote` route. Cancelling setup while saving or connecting prevents a later +automatic switch. A profile or SSH tunnel already created is not rolled back; +you can manage it from the directory. Adding the same connection settings again +reuses that entry, without renaming it or disconnecting an open view. This connects to the nanobot **already running on the server**. It does not install a worker, clone a workspace, move conversations, or start a second bot. It is separate from remote execution/worker deployment. +## Quick pairing: copy a command, follow a link back + +For a Linux server with this version of nanobot installed, you do not need to +prepare a local SSH key or know the service account/config path: + +1. In your **local** WebUI choose **Add server → Copy command**. The command is + prepared when setup opens; **View command** lets you inspect it before running. + After a successful copy, the dialog shows what to do in your server terminal. + This is a clipboard confirmation, not a claim that the server is connected. + **Other ways → Requirements & help** contains prerequisites and expiry details. +2. Open your cloud provider's server terminal. Run the command in the environment + where nanobot is installed (activate its virtual environment for source installs). + The command discovers the default config and named nanobot systemd services; + choose a configuration if there is more than one. Provide the server's reachable + IP/hostname and an existing non-root SSH login account when prompted. + A single existing login account (including the original account under sudo) + is selected automatically and shown in the authorization summary. A global + server address reported by the SSH session can also be selected automatically; + private/NAT addresses are never guessed. Use `--ssh-user` or `--host` to override. +3. Review the **full nanobot access** authorization on the server and confirm it. + If nanobot runs as another service account, the server administrator must run + this step. Pairing does not install sudo rules or weaken config permissions. +4. Open the terminal's **Return to nanobot** link on the same computer and in the + same browser profile that started pairing. The local WebUI opens the server + confirmation directly; review its identity and access, then choose **Connect**. + The link does not authorize or connect automatically. If the terminal cannot + open links, choose **Other ways → Use a connection code instead** and paste the returned + `nbpc1.…` code, then **Review connection**. Both paths use the same verification. + +The return link targets only an HTTP loopback origin (`127.0.0.1`, `localhost`, +or `[::1]`). Its fragment contains an encrypted receipt, not a plaintext admin +secret, and is scrubbed before the WebUI signs in. A new tab can continue the +request even if the original setup tab was closed. Pending keys remain on the +local backend for the ten-minute invitation lifetime; abandoned requests are +cleaned when a new request is prepared. A link opened on another machine, an +expired request, or a modified code fails closed. Native/non-loopback origins +continue to use the code fallback. Existing local authentication is still required. + +No relay, public WebUI, uploaded private key, QR scan or new firewall rule is +involved. The public invitation expires after ten minutes. The returned code is +encrypted for that local instance; another computer/request cannot import it. +The server host key is pinned from the code copied through your trusted terminal. +Do not accept a connection code supplied by someone you do not trust. + +The dedicated device SSH key expires after 90 days. OpenSSH `restrict` disables +shell-adjacent features and all SSH forwarding; a forced, fixed Python stdio +bridge connects only to the selected loopback nanobot port. It cannot execute +the client's SSH command. No extra daemon is installed or started. The server +requires OpenSSH with `restrict` and `expiry-time` support, `/usr/bin/python3`, +an Ed25519 host key, and the conventional `~/.ssh/authorized_keys` layout. +Custom SSH policies/layouts may reject the grant; use existing SSH settings in +that case. Windows servers and containers are not supported by quick pairing. + +This is still **full access to nanobot**, not read-only access. Its configured +tools may themselves run commands or modify files. The WebUI credential stays +in the local backend, encrypted at rest alongside a private local decryption key +and dedicated SSH identity (directories `0700`, files `0600`). This protects +against other OS users, not compromise of your logged-in account. Provider keys +are not exported by the pairing protocol. Changes to the remote WebUI secret or +port require pairing again; they are not silently refreshed through sudo. + +SSH network reachability is still required. Pairing cannot fix a blocked port or +VPN route. A failed connection keeps the paired profile for retry. **Network +route…** can explicitly reuse a saved connection's proxy/bound-interface route +to the same host, without copying its identity settings. Jump-host routes should +continue to use the ordinary SSH connection flow. + +If the server rejects a paired device key, the UI asks you to pair again rather +than unlock an unrelated SSH agent. This can happen after revocation or expiry. + +**Disconnect** closes local streams. **Forget** removes the local directory entry, +including that device's local pairing keys, but does not revoke server authorization. +To revoke, run the command displayed +in the connection details on the server: + +```bash +nanobot remote revoke DEVICE_ID --ssh-user LOGIN_ACCOUNT +``` + +Only that device's exact managed key entry is removed; existing login keys stay +unchanged. Close any already-open remote sessions too: removing an authorized +key prevents new SSH authentication, not existing sessions. If setup is cancelled +after server authorization, use the revoke command printed in that terminal. +Re-pairing after expiry uses a new independent key, not an extension of an old grant. + +## Existing SSH setup: server, then nanobot + +The setup dialog separates **Server** (SSH login) from **nanobot** (which +installation to open). Start with an address or an existing SSH host. You do +not need to know nanobot's config path in advance. + +After SSH signs in, a read-only check looks for the selected account's config +and up to eight named `nanobot*.service` systemd units. It reads service metadata +and checks config-file locations; it does not read their contents, scan other +users' home directories, run sudo, install software or change permissions. +One configuration belonging to the login account opens automatically. Multiple +configurations are shown as choices. A service owned by another account always +requires an explicit **Open nanobot** choice, showing that account and path; +opening still requires existing passwordless sudo permission. + +If nothing is found, the dialog confirms **SSH connected** and asks for the +server's config path and optional service account. Docker, custom service names, +user services and non-systemd deployments may need this manual step. Failure to +find a config is not proof that nanobot is absent. Finding a config is also not +proof that its WebUI is running: the normal authenticated gateway check still +happens before opening. + +SSH failures keep the entered address and offer **SSH login settings** for the +local key path, SSH config and port. Connection refusal, name resolution, +connection closure and authentication rejection have distinct messages. The +application does not infer a missing key from a closed connection, nor change +VPN, proxy or network-interface settings automatically. A custom SSH config +outside standard locations must still be explicitly supplied by its owner. + ## Find a server you already use -nanobot lists named hosts from `~/.ssh/config` and the system SSH config, including -ordinary `Include` files. Search by alias, then select a host to review its setup. -If your configuration lives elsewhere, expand **Use another SSH config file** -and enter its local path. Returning from setup keeps the previous list and search. +The add/edit dialog suggests named hosts from `~/.ssh/config` and the system SSH +config, including ordinary `Include` files. Typing in **SSH address** filters +these suggestions without a separate search field. Selecting a host fills the +address; it does not connect until you choose **Connect**. Arrow keys navigate +the suggestions. If your configuration lives elsewhere, expand **Connection +options** and select the file beside **SSH config file**, or enter its local path. +Suggestions update automatically; no separate file-reading step is needed. +The private key field also has a native file chooser. Selecting a file returns +only its path: it does not upload, copy or read the private key. Cancelling leaves +the existing path unchanged. Headless hosts can use the manual path fields. Discovery is passive: it reads host names and source paths, not private keys, and does not contact servers or execute SSH hooks. Wildcard and negated patterns @@ -33,13 +166,22 @@ you can still enter an alias manually. Discovery is capped at 200 hosts, 64 file At connection time, the system SSH client resolves your existing `User`, `Port`, `IdentityFile`, jump hosts and other connection settings. An empty port field inherits SSH configuration instead of overriding it with 22. Listing a host -does not mean nanobot is installed there. Enter an alias or address, not a full -shell command. +does not mean nanobot is installed there. + +You can also paste a simple command, for example +`ssh -p 2222 -i "~/.ssh/team key" ubuntu@your-server`. The address field imports +`-p` (port), `-i` (key path), `-F` (config path) and `-l` (login user) into the +existing Connection options. Review these before connecting. Quoted paths can +contain spaces, including Windows paths. This is an importer, not a terminal: +remote commands, shell expansions, repeated options and other flags are rejected, +not executed or silently discarded. Keep advanced options such as `ProxyJump` +in your SSH config and enter the alias. An interactive alias's `RemoteCommand` +and forced TTY are disabled for the fixed nanobot probe. ## Prerequisites - Run the local WebUI on a loopback address, using the system OpenSSH client. -- Your SSH key must already have access to the server. Encrypted keys should +- For **existing SSH settings**, your key must already have access to the server. Encrypted keys should be unlocked in the system SSH agent. Interactive SSH passwords are not collected by this UI. - The remote server needs `python3` and an already running nanobot WebUI with @@ -47,18 +189,22 @@ shell command. - The remote gateway must support the authenticated `/webui/terminal` identity probe, protocol version 1, and have the WebUI bundle installed. The initial transport supports HTTP on the server's loopback address; SSH - encrypts the connection. A configured public WebSocket URL is not supported. + encrypts the connection. A configured public WebSocket URL or trusted-proxy + authentication is not supported by this SSH connection mode. If this machine has never connected to the server, nanobot displays its SSH fingerprint. Compare it with the server console or your administrator before -confirming. The public key is pinned for this connection, without changing +confirming in the same dialog. **Back** returns to the filled-in form when adding +a server. The public key is pinned for this connection, without changing your system `known_hosts`. A **changed** host key is blocked, not automatically accepted. Jump-host-only or non-Ed25519 hosts can use a previously verified system SSH configuration instead of the in-app first-contact verifier. -## Advanced options +## Connection options -Most setups only need the SSH address. Expand **Advanced** when necessary: +Most setups only need the SSH address. Expand **Connection options** when necessary. +You can also give the server a recognizable name here; otherwise its address is +used as the name. | Option | Meaning | | --- | --- | @@ -70,8 +216,10 @@ Most setups only need the SSH address. Expand **Advanced** when necessary: For a service installation, the SSH login and nanobot owner may differ. For example, you might sign in as `ubuntu`, with nanobot running as `nanobot` and -its config in `/var/lib/nanobot/.nanobot/config.json`. Enter those last two -values in Advanced. The connection does not grant new sudo privileges. +its config in `/var/lib/nanobot/.nanobot/config.json`. The discovery step offers +these values when it finds the service; otherwise use **Specify a different +location** in the nanobot step. Editing a saved connection also exposes these +fields. The connection does not grant new sudo privileges. ## Using the remote instance @@ -100,6 +248,12 @@ return local without covering their controls. Refreshing restores the selected remote instance. A failed connection stays on a remote error screen; it never silently redirects work to your local agent. The selected server ID is stored per browser tab, without credentials. +When the page becomes visible again or the browser reports network recovery, +nanobot immediately rechecks existing connections. It does not reload the remote +view, switch hosts, or resend messages. If the connection remains unavailable, +use **Reconnect**. Different aliases resolving to the same already-connected +gateway are rejected; choose its existing entry in the host switcher. Separate +nanobot instances on one server can still use separate profiles and config paths. - **Switching hosts**, including returning local, keeps both pages mounted and keeps SSH connected. Each host retains its own chat, unsent draft, scroll @@ -129,15 +283,47 @@ The selected server ID is stored per browser tab, without credentials. The local connection directory is stored beside the local config under `webui/remote-instances.json`. It contains connection metadata, not private-key contents or model/channel credentials. A stable loopback port per saved server -keeps browser preferences scoped to that server. Port conflicts fail explicitly; -nanobot does not attach to an unrelated listener. +keeps browser preferences scoped to that server. Changing the SSH target, config +path, service account or identity file assigns a fresh browser origin, rather +than loading the previous instance's drafts. The adjacent +`remote-origin-ports.json` records previously used ports, without credentials; +these ports are not assigned to new targets, even after forgetting a profile. +Keep that file alongside the connection directory when moving local settings. +Port conflicts fail explicitly; nanobot does not attach to an unrelated listener. + +The local gateway owns a browser-facing proxy and a separate, private SSH +transport. Browser login, API, WebSocket and media credentials are local +capabilities: they cannot authenticate to the remote gateway. The remote +credentials stay in backend memory. System SSH's private stdin/stdout pipes, +SSH configuration and host-key verification still secure the upstream transport. +Disconnecting or forgetting closes active requests but retains disabled +listeners until local gateway shutdown. Reconnecting the same saved instance +reuses its browser origin. An offline profile can be edited without first +disconnecting it in another tab. + +Closing the local gateway drains proxy requests before releasing its private +transport. If an old tab retries the browser address after shutdown, it sends +only local capabilities from the stopped proxy, not a remote login credential. +Close old tabs anyway: after shutdown another local process can serve content +at that address. This does not isolate nanobot from malware running as you. +On Windows, exclusive socket ownership may delay reusing a port after shutdown; +retry later if it remains occupied. Nanobot does not weaken socket ownership +to force a reconnect. SSH authenticates the server. A read-only, fixed Python probe retrieves only WebUI login information from its config. The gateway's protocol and runtime ID -are verified before navigation. The WebUI credential is held by the live -connection and passed in the remote view's URL fragment, not an HTTP query or -local model configuration. The remote WebUI uses its existing browser login -storage. Nothing opens a public administration port or forwards your SSH agent. +are verified before navigation. Only a local proxy credential is passed in the +remote view's URL fragment and stored by its existing login UI. Local gateway +restart replaces that credential and invalidates local token/media mappings; +reopening the saved connection handles this without an extra login step. +Nothing opens a public administration port or forwards your SSH agent. + +**Upgrading the earlier remote-connection prototype:** it passed the remote +WebUI login secret to browser storage. This version retires those old browser +origins, but cannot revoke a secret already saved in an old tab. Close those +tabs, clear their browser site data, and rotate the remote WebUI login secret +to invalidate the old credential. This migration does not rotate credentials +or restart your server automatically. Remote-connection actions require an authenticated local WebUI connection, a loopback-bound gateway, and local request origin. They are unavailable from a @@ -146,6 +332,12 @@ access; permission to mention nanobot in Linear is **not** that permission. Common errors explain whether SSH authentication, a missing config, a service account, WebUI authentication, protocol compatibility or networking failed. +Key-agent refusal, unsafe key-file permissions, invalid SSH configuration and +server-side port-forwarding denial have separate recovery hints. Login banners +are ignored when reading the framed probe result. A failed probe is distinct +from an invalid nanobot configuration; raw SSH output and credentials aren't +displayed in error messages. If SSH works in a terminal but not in nanobot, +check that nanobot was started with access to the same system SSH agent. Configurations whose WebUI secret is supplied only by a service environment, interactive SSH passwords, and remote WebUIs with a public WebSocket URL need additional setup; this flow does not silently weaken their authentication. diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 3a20e1319..83c2cc795 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -97,6 +97,11 @@ app = typer.Typer( console = Console() +# Server-console pairing stays outside the agent/gateway lifecycle. +from nanobot.cli.remote import app as remote_app # noqa: E402 + +app.add_typer(remote_app, name="remote") + def version_callback(value: bool): if value: console.print(f"{__logo__} nanobot v{__version__}") diff --git a/nanobot/cli/remote.py b/nanobot/cli/remote.py new file mode 100644 index 000000000..9cac4b949 --- /dev/null +++ b/nanobot/cli/remote.py @@ -0,0 +1,139 @@ +"""Server-console commands for explicit remote WebUI device authorization.""" + +from __future__ import annotations + +import ipaddress +import os +import subprocess +import sys +import time +from pathlib import Path + +import typer +from click import IntRange + +app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.") + + +def _default_host() -> str: + """Use only a globally reachable address reported by this SSH session. + + A cloud's outbound address or a NAT/private address is not evidence of the + inbound SSH destination. Do not contact an external IP lookup service. + """ + fields = os.environ.get("SSH_CONNECTION", "").split() + try: + address = ipaddress.ip_address(fields[2]) if len(fields) == 4 else None + return str(address) if address and address.is_global else "" + except ValueError: + return "" + + +def _default_ssh_user() -> str | None: + """Suggest the existing login account, including when invoked through sudo.""" + import pwd + + current = pwd.getpwuid(os.getuid()) + if current.pw_uid: + return current.pw_name + users = [u.pw_name for u in pwd.getpwall() if 1000 <= u.pw_uid < 65534 and u.pw_shell.endswith(("/bash", "/sh", "/zsh"))] + sudo_user = os.environ.get("SUDO_USER") + if sudo_user in users: + return sudo_user + return users[0] if len(users) == 1 else None + + +@app.command() +def pair( + request: str = typer.Argument(help="Public pairing request copied from your local WebUI"), + host: str = typer.Option("", help="Server IP or hostname reachable from your computer"), + ssh_user: str = typer.Option("", help="Existing non-root SSH login account"), + port: int = typer.Option(22, min=1, max=65535, help="Existing SSH port; not changed"), + config: Path | None = typer.Option(None, help="Existing nanobot config; discovered if omitted"), +) -> None: + """Run in your server terminal, then open the returned link on your computer.""" + from nanobot.webui.remote_pairing import fingerprint, read_request, return_link + from nanobot.webui.remote_ssh import RemoteError + + try: + if sys.platform != "linux": + raise RemoteError("pair_linux_required") + from nanobot.webui.remote_pair_server import authorize, metadata + + invitation = read_request(request) + host_key = " ".join(Path("/etc/ssh/ssh_host_ed25519_key.pub").read_text().split()[:2]) + if config is None: + from nanobot.webui.remote_discovery import ( + _LOCATE, # pyright: ignore[reportPrivateUsage] + RemoteInspection, + ) + + result = subprocess.run([sys.executable, "-c", _LOCATE, str(Path.home() / ".nanobot/config.json")], capture_output=True, text=True, timeout=8) + records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line] + candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else [] + if len(candidates) == 1: + config = Path(candidates[0].config_path) + elif candidates: + for index, item in enumerate(candidates, 1): + typer.echo(f'{index}. {item.service or "nanobot"} — {item.config_path}') + choice = int(typer.prompt("Which nanobot?", type=IntRange(1, len(candidates)))) + config = Path(candidates[choice - 1].config_path) + else: + config = Path(typer.prompt("Path to your nanobot config")) + config = config.expanduser().resolve() + details = metadata(config) + if not ssh_user: + ssh_user = _default_ssh_user() or typer.prompt("SSH login account") + if not host: + host = _default_host() or typer.prompt("Server public IP or hostname (shown in your cloud console)") + typer.echo(f"\nAuthorize {invitation.label} to use nanobot on {ssh_user}@{host}?\nConfig: {config}\nServer fingerprint: {fingerprint(host_key)}") + typer.echo("This grants full nanobot WebUI access, including configured tools and settings.\nA dedicated SSH key can only reach this nanobot port; no shell or other forwarding.\nAuthorization lasts 90 days. No existing keys, firewall rules or model settings change.") + typer.confirm("Authorize this computer?", abort=True, default=False) + # Check the service is running before granting access; no credential is sent. + import socket + + with socket.create_connection(("127.0.0.1", details["port"]), timeout=5): + pass + code = authorize(invitation, host=host, user=ssh_user, ssh_port=port, config=config, + host_key=host_key, until=int(time.time()) + 90 * 86400) + link = return_link(invitation, code) + if link: + typer.echo("\nReturn to nanobot on your computer to finish connecting:") + typer.echo("Open this link in the same computer/browser that started pairing.\n") + typer.echo(link) + typer.echo("\nIf your terminal cannot open links, paste this connection code into nanobot:\n") + else: + typer.echo("\nPaste this connection code into the same local nanobot window:\n") + typer.echo(code) + typer.echo(f"\nTo revoke new connections: nanobot remote revoke {invitation.id} --ssh-user {ssh_user}") + typer.echo("Close any already-open remote sessions as well. Re-pair after changing the WebUI secret or port.") + except (OSError, ValueError, KeyError, subprocess.SubprocessError, RemoteError) as exc: + typer.echo(f"Pairing not completed: {str(exc) if isinstance(exc, RemoteError) else 'check server config, login account and SSH installation'}. Existing settings were not reset.", err=True) + if str(exc) == "config_permission": + typer.echo("The nanobot config belongs to another account. Run this command in its installation environment as the server administrator, or ask that administrator to pair it. Do not make the config publicly readable.", err=True) + raise typer.Exit(1) from None + + +@app.command() +def revoke(device: str, ssh_user: str = typer.Option("", help="SSH account used when pairing")) -> None: + """Remove only this device's managed SSH authorization, preserving other keys.""" + import getpass + + from nanobot.webui.remote_ssh import RemoteError + + try: + if sys.platform != "linux": + raise RemoteError("pair_linux_required") + from nanobot.webui.remote_pair_server import as_account + + user = ssh_user or getpass.getuser() + typer.confirm(f"Revoke device {device} for SSH account {user}?", abort=True, default=False) + as_account(user, "revoke", {"id": device}) + typer.echo("Authorization removed. Already-open SSH sessions must also be closed.") + except (OSError, KeyError, RemoteError, subprocess.SubprocessError): + typer.echo("Could not revoke. Check the device ID and run as the SSH account or server administrator.", err=True) + raise typer.Exit(1) from None + + +if __name__ == "__main__": + app() diff --git a/nanobot/webui/native_folder_picker.py b/nanobot/webui/native_folder_picker.py index 37a91dbcc..e97df8ec3 100644 --- a/nanobot/webui/native_folder_picker.py +++ b/nanobot/webui/native_folder_picker.py @@ -1,4 +1,4 @@ -"""Native directory picker used by a locally hosted WebUI.""" +"""Native path pickers used by a locally hosted WebUI; never read file contents.""" from __future__ import annotations @@ -9,6 +9,7 @@ import sys from contextlib import suppress from dataclasses import dataclass from pathlib import Path +from typing import Literal _PICKER_TIMEOUT_SECONDS = 300 _COMMON_ENV_KEYS = ( @@ -66,7 +67,8 @@ class _PickerCommand: cancel_markers: tuple[str, ...] = () -def _picker_command() -> _PickerCommand | None: +def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerCommand | None: + title = "Select Workspace Directory" if kind == "folder" else "Select SSH key or configuration file" if sys.platform == "darwin": executable = shutil.which("osascript") if executable is None: @@ -75,9 +77,9 @@ def _picker_command() -> _PickerCommand | None: argv=( executable, "-e", - 'set selectedFolder to choose folder with prompt "Select Workspace Directory"', + f'set selectedPath to choose {kind} with prompt "{title}"', "-e", - "POSIX path of selectedFolder", + "POSIX path of selectedPath", ), cancel_codes=frozenset({1}), cancel_markers=("user canceled", "(-128)"), @@ -87,14 +89,22 @@ def _picker_command() -> _PickerCommand | None: executable = shutil.which("powershell.exe") or shutil.which("powershell") if executable is None: return None + dialog = ( + "$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;" + f"$dialog.Description='{title}';" + "$dialog.ShowNewFolderButton=$true;" + ) if kind == "folder" else ( + "$dialog=New-Object System.Windows.Forms.OpenFileDialog;" + f"$dialog.Title='{title}';" + "$dialog.CheckFileExists=$true;$dialog.Multiselect=$false;" + ) + selected = "SelectedPath" if kind == "folder" else "FileName" script = ( "Add-Type -AssemblyName System.Windows.Forms;" - "$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;" - "$dialog.Description='Select Workspace Directory';" - "$dialog.ShowNewFolderButton=$true;" + + dialog + "if($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){" "[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();" - "[Console]::Out.Write($dialog.SelectedPath)}" + f"[Console]::Out.Write($dialog.{selected})}}" ) return _PickerCommand( argv=( @@ -117,15 +127,15 @@ def _picker_command() -> _PickerCommand | None: argv=( zenity, "--file-selection", - "--directory", - "--title=Select Workspace Directory", + *(("--directory",) if kind == "folder" else ()), + f"--title={title}", ), cancel_codes=frozenset({1}), ) kdialog = shutil.which("kdialog") if kdialog is not None: return _PickerCommand( - argv=(kdialog, "--getexistingdirectory", str(Path.home())), + argv=(kdialog, "--getexistingdirectory" if kind == "folder" else "--getopenfilename", str(Path.home())), cancel_codes=frozenset({1}), ) return None @@ -167,7 +177,15 @@ async def _stop_process(process: asyncio.subprocess.Process) -> None: async def pick_native_folder() -> str | None: """Open the platform directory picker and return an existing absolute path.""" - command = _picker_command() + return await _pick_native_path(_picker_command(), "directory") + + +async def pick_native_file() -> str | None: + """Choose an existing local file without opening, uploading or copying it.""" + return await _pick_native_path(_picker_command("file"), "file") + + +async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str | None: if command is None: raise NativeFolderPickerError("native folder picker is unavailable on this host") @@ -206,6 +224,6 @@ async def pick_native_folder() -> str | None: if not selected: return None path = Path(selected).expanduser() - if not path.is_absolute() or not path.is_dir(): - raise NativeFolderPickerError("native folder picker returned an invalid directory") + if not path.is_absolute() or not (path.is_dir() if kind == "directory" else path.is_file()): + raise NativeFolderPickerError(f"native path picker returned an invalid {kind}") return str(path) diff --git a/nanobot/webui/remote_discovery.py b/nanobot/webui/remote_discovery.py new file mode 100644 index 000000000..ccb38732b --- /dev/null +++ b/nanobot/webui/remote_discovery.py @@ -0,0 +1,133 @@ +"""Locate remote nanobot configurations without reading credentials or using sudo. + +Only the selected account's config and named nanobot systemd units are inspected. +An alternate service account is returned as a choice, never silently impersonated. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, run_check + +_LOCATE = r''' +import getpass, json, os, pathlib, re, shlex, socket, stat, subprocess, sys +try: + import pwd +except ImportError: + pwd = None + +candidates = [] +incomplete = False +current_user = pwd.getpwuid(os.getuid()).pw_name if pwd else getpass.getuser() + +def add(path, user="", service=""): + global incomplete + if len(candidates) >= 8: + incomplete = True + return + try: + path = pathlib.Path(path).expanduser() + if not path.is_absolute(): + return + exists = stat.S_ISREG(path.stat().st_mode) + except PermissionError: + # A declared service config can be offered even when the SSH account + # cannot stat it. The later explicit choice still needs sudo permission. + exists = bool(service) + except (OSError, ValueError): + return + user = "" if user == current_user else user + item = {"config_path": str(path), "runtime_user": user, "service": service} + if exists and not any(x["config_path"] == item["config_path"] and x["runtime_user"] == user for x in candidates): + candidates.append(item) + +add(sys.argv[1]) + +def systemctl(*args): + result = subprocess.run(["systemctl", *args, "--no-pager"], + capture_output=True, text=True, timeout=2) + if result.returncode: + raise OSError("systemctl unavailable") + return result.stdout + +try: + units = [line.split()[0] for line in systemctl("list-units", "--all", "--plain", "--no-legend", "nanobot*.service").splitlines() if line.split()] + units = [name for name in units if re.fullmatch(r"nanobot[a-zA-Z0-9_.@-]*\.service", name)] + incomplete = len(units) > 8 + if units and pwd: + records = systemctl("show", *units[:8], "--property=Id,User,ExecStart,WorkingDirectory") + for block in records.strip().split("\n\n"): + fields = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) + service = fields.get("Id", "") + if service not in units[:8]: + continue + user = fields.get("User") or "root" + if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_-]*", user): + continue + try: + home = pathlib.Path(pwd.getpwnam(user).pw_dir) + tokens = shlex.split(fields.get("ExecStart", "")) + except (KeyError, ValueError): + incomplete = True + continue + config = None + for index, token in enumerate(tokens): + if token.startswith("--config="): + config = token.split("=", 1)[1] + break + if token in {"--config", "-c"} and index + 1 < len(tokens): + config = tokens[index + 1] + break + if config and ("$" in config or "%" in config): + incomplete = True + continue + if config: + if config.startswith("~/"): + path = home / config[2:] + elif pathlib.Path(config).is_absolute(): + path = pathlib.Path(config) + else: + path = pathlib.Path(fields.get("WorkingDirectory") or str(home)) / config + else: + path = home / ".nanobot/config.json" + add(path, user, service) +except (OSError, subprocess.TimeoutExpired): + incomplete = True + +print("\n\x1eNANOBOT_REMOTE:" + json.dumps({"hostname": socket.gethostname(), "candidates": candidates, "incomplete": incomplete})) +''' + + +class RemoteLocation(BaseModel): + model_config = ConfigDict(extra="ignore", strict=True) + + config_path: str = Field(min_length=1, max_length=2048) + runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$") + service: str = Field(default="", max_length=256, pattern=r"^([a-zA-Z0-9_.@-]+\.service)?$") + + @field_validator("config_path") + @classmethod + def safe_path(cls, value: str) -> str: + return RemoteProfile.safe_path(value) + + +class RemoteInspection(BaseModel): + model_config = ConfigDict(extra="ignore", strict=True) + + hostname: str = Field(min_length=1, max_length=253) + candidates: list[RemoteLocation] = Field(max_length=8) + incomplete: bool + + +async def inspect(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]: + # Inspection is always performed as the SSH login, even when an old profile + # has a service account. Discovery must not implicitly escalate privileges. + result = await run_check(profile.model_copy(update={"runtime_user": ""}), _LOCATE, known_hosts) + try: + return RemoteInspection.model_validate(result).model_dump() + except ValidationError: + raise RemoteError("probe_failed") from None diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py index 35aeea115..fd1ad34b1 100644 --- a/nanobot/webui/remote_instances.py +++ b/nanobot/webui/remote_instances.py @@ -18,13 +18,18 @@ 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_proxy import RemoteProxy from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel +_HEALTH_TIMEOUT_SECONDS = 12 + 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) + proxy_origin: bool = False + pair_id: str = "" @dataclass @@ -34,7 +39,9 @@ class Connection: hostname: str config_path: str gateway_id: str + proxy: RemoteProxy error: str = "" + paired: bool = False class RemoteInstances: @@ -43,11 +50,19 @@ class RemoteInstances: def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None: self.path = directory / "remote-instances.json" self.local_gateway_id = local_gateway_id + # Public identity, not an authentication capability. A new local manager + # cannot renew a cached iframe's old proxy credentials after restart. + self._view_session = uuid.uuid4().hex self.connections: dict[str, Connection] = {} + self._proxies: dict[int, RemoteProxy] = {} self._lock = asyncio.Lock() + self._picker_lock = asyncio.Lock() self._unverified: dict[str, tuple[str, str, float]] = {} self._unknown_hosts: set[str] = set() self._closed = False + from nanobot.webui.remote_pairing import PairStore + + self.pairing = PairStore(directory) def _known_hosts(self, key: str) -> Path: return self.path.parent / "remote-hosts" / key @@ -75,39 +90,108 @@ class RemoteInstances: )) self.path.chmod(0o600) + def _remember_origins(self, profiles: dict[str, _SavedProfile], port: int = 0) -> set[int]: + # Browser storage outlives edits, Forget and gateway restarts. Keep a + # small append-only port ledger, including pre-ledger saved profiles, + # so a new target never inherits a retired target's browser origin. + path = self.path.with_name("remote-origin-ports.json") + try: + raw: object = json.loads(path.read_text()) if path.exists() else [] + if not isinstance(raw, list): + raise ValueError + ports: set[int] = set() + for value in cast(list[object], raw): + if type(value) is not int or not 1 <= value <= 65535: + raise ValueError + ports.add(value) + except (ValueError, TypeError, OSError): + raise RemoteError("profile_store_invalid") from None + ports.update(profile.local_port for profile in profiles.values() if profile.local_port) + if port: + ports.add(port) + path.parent.mkdir(parents=True, exist_ok=True) + _write_text_atomic(path, json.dumps(sorted(ports))) + path.chmod(0o600) + return ports + 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() - ]} + profiles: list[dict[str, Any]] = [] + for key, profile in self._read().items(): + connection = self.connections.get(key) + error = (connection.error or ("" if connection.tunnel.active else "ssh_unreachable")) if connection else "disconnected" + item = {"id": key, **profile.model_dump(exclude={"local_port", "proxy_origin", "pair_id"}), + "connected": connection is not None and not error, + "connection_error": error} + if connection: + item["gateway_id"] = connection.gateway_id + item["view_id"] = self._view_session + if profile.pair_id: + item.update(paired=True, revoke_command= + f"nanobot remote revoke {profile.pair_id} --ssh-user {profile.host.split('@')[0]}") + expiry = self.pairing.authorization_until(profile.pair_id) + if expiry is not None: + item["authorized_until"] = expiry + profiles.append(item) + return {"available": True, "machine_name": socket.gethostname(), "profiles": profiles} 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: + # Hold a lifetime lease through every credential-bearing request. Final + # shutdown cannot release the listeners halfway through a health check. + try: + # Includes lock contention and all response reads, not just each + # socket read. Return the directory before the browser's 20s budget. + async with asyncio.timeout(_HEALTH_TIMEOUT_SECONDS): + async with self._lock: + await asyncio.gather(*(self._check(item) for item in self.connections.values())) + except TimeoutError: + pass + return self.snapshot() + + async def _check(self, connection: Connection) -> None: + if not connection.tunnel.active: + connection.error = "ssh_unreachable" + return + try: + async with httpx.AsyncClient(timeout=20, 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 in {401, 403}: + connection.error = "remote_auth_failed" + elif response.status_code != 200: + connection.error = "remote_unreachable" + else: + raw_identity = response.json() + identity = cast(dict[str, Any], raw_identity) if isinstance(raw_identity, dict) else {} + if (type(identity.get("protocolVersion")) is not int + or identity.get("protocolVersion") != 1 or not isinstance(identity.get("gatewayId"), str)): + connection.error = "incompatible_gateway" + elif identity["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() + except (httpx.HTTPError, ValueError, AttributeError): + connection.error = connection.tunnel.error or "remote_unreachable" + if connection.paired and connection.error == "ssh_auth_failed": + connection.error = "pair_authorization_rejected" + except asyncio.CancelledError: + connection.error = "remote_unreachable" + raise async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]: + if action == "pick_file": + from nanobot.webui.native_folder_picker import NativeFolderPickerError, pick_native_file + + if self._closed or self._picker_lock.locked(): + raise RemoteError("file_picker_unavailable") + # The route is authenticated and loopback-only. No caller-provided + # command, file content or initial directory enters the OS dialog. + async with self._picker_lock: + try: + return {"path": await pick_native_file()} + except NativeFolderPickerError: + raise RemoteError("file_picker_unavailable") from None if action == "discover": from nanobot.webui.ssh_config import discover_hosts @@ -121,31 +205,114 @@ class RemoteInstances: raise RemoteError("local_io_error") profiles = self._read() key = str(payload.get("id", "")) + if action == "pair_start": + return_origin = payload.get("return_origin", "") + if not isinstance(return_origin, str): + raise RemoteError("pair_invalid") + return self.pairing.start(return_origin) + if action == "pair_cancel": + self.pairing.cancel(key) + return {"cancelled": True} + if action in {"pair_preview", "pair_finish"}: + code = payload.get("code", "") + if not isinstance(code, str): + raise RemoteError("pair_invalid") + if action == "pair_preview": + return self.pairing.preview(key, code) + if len(profiles) >= 20 and key not in profiles: + raise RemoteError("profile_limit") + # Completion is idempotent. No browser-provided host/path/key is + # trusted as a substitute for the encrypted server receipt. + if key in profiles: + return {"id": key, **self.snapshot()} + receipt = self.pairing.finish(key, code) + profile = self.pairing.profile(receipt) + known = self._known_hosts(key) + known.parent.mkdir(parents=True, exist_ok=True) + _write_text_atomic(known, "nanobot-remote " + receipt.host_key + "\n") + known.chmod(0o600) + profiles[key] = _SavedProfile(**profile.model_dump(), pair_id=key) + self._write(profiles) + return {"id": key, **self.snapshot()} if action == "save": profile = RemoteProfile.model_validate(payload.get("profile")) if key and key not in profiles: raise RemoteError("profile_not_found") + if key and profiles[key].pair_id: + raise RemoteError("pair_managed") + if key and profiles[key].model_dump(include=set(RemoteProfile.model_fields)) == profile.model_dump(): + # Retrying a slow browser load must not count as editing a + # live SSH connection. Real changes still require disconnect. + return {"id": key, **self.snapshot()} + if not key: + destination = profile.model_dump(exclude={"name"}) + for saved_key, saved in profiles.items(): + if saved.model_dump(include=set(destination)) == destination: + # Reopening Add after a failed attempt should reuse + # its entry, without renaming it or closing live views. + return {"id": saved_key, **self.snapshot()} 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") + connection = self.connections.get(key) + if connection: + if connection.tunnel.active and not connection.error: + raise RemoteError("disconnect_before_edit") + # A fresh tab offers Edit for an offline profile. Release its + # failed tunnel here instead of demanding a hidden Disconnect. + await connection.proxy.pause() + del self.connections[key] target_changed = key in profiles and any( getattr(profiles[key], field) != getattr(profile, field) for field in ("host", "port", "ssh_config") ) + instance_changed = target_changed or (key in profiles and any( + getattr(profiles[key], field) != getattr(profile, field) + for field in ("config_path", "runtime_user", "identity_file") + )) + if instance_changed: + self._remember_origins(profiles) + local_port = profiles[key].local_port if key in profiles and not instance_changed else 0 + proxy_origin = bool(local_port and profiles[key].proxy_origin) + profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port, + proxy_origin=proxy_origin) + self._write(profiles) 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": + if action == "pair_route": + profile = profiles[key] + if not profile.pair_id: + raise RemoteError("pair_invalid") + existing = self.connections.get(key) + if existing and existing.tunnel.active and not existing.error: + raise RemoteError("disconnect_before_edit") + route_id = str(payload.get("route_id", "")) + if route_id: + source = profiles.get(route_id) + if source is None or source.pair_id: + raise RemoteError("profile_not_found") + config = await remote_ssh.pairing_route(source, profile.host.split("@")[-1]) + path = self.pairing.path(profile.pair_id) / "ssh_route" + _write_text_atomic(path, config) + path.chmod(0o600) + profile.ssh_config = str(path) + else: + profile.ssh_config = "" + self._write(profiles) + return self.snapshot() + if action in {"connect", "inspect"}: try: + if action == "inspect": + if profiles[key].pair_id: + raise RemoteError("pair_managed") + from nanobot.webui.remote_discovery import inspect + + return await inspect(profiles[key], self._known_hosts(key)) return await self._connect(key, profiles[key]) except RemoteError as exc: if str(exc) == "host_key_unknown": @@ -175,8 +342,11 @@ class RemoteInstances: if action in {"disconnect", "remove"}: connection = self.connections.pop(key, None) if connection: - await connection.tunnel.close() + await connection.proxy.pause() if action == "remove": + self._remember_origins(profiles) + if profiles[key].pair_id: + self.pairing.forget(profiles[key].pair_id) del profiles[key] self._write(profiles) self._known_hosts(key).unlink(missing_ok=True) @@ -188,25 +358,41 @@ class RemoteInstances: 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} + "url": f"{connection.proxy.origin}/#/?bootstrapSecret={quote(connection.proxy.secret, safe='')}", + "gateway_id": connection.gateway_id, "view_id": self._view_session} async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]: existing = self.connections.get(key) if existing: - await self.health() + await self._check(existing) if not existing.error: return self._launch(key, profile, existing) - await existing.tunnel.close() + await existing.proxy.pause() 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) + transport: RemoteProfile = profile + if profile.pair_id: + data = self.pairing.connection(profile.pair_id) + transport = remote_ssh.PairedSSHProfile(**profile.model_dump(include=set(RemoteProfile.model_fields))) + else: + data = await remote_ssh.probe(profile, known_hosts) + used_ports = self._remember_origins(self._read()) + # Retire browser origins from the earlier transparent tunnel. Those + # origins may still contain remote secrets in old tabs/localStorage. + local_port = profile.local_port if profile.proxy_origin else 0 + proxy = self._proxies.get(local_port) + if proxy is not None: + tunnel = proxy.tunnel + tunnel.resume(transport, data["port"], known_hosts) + else: + tunnel = await remote_ssh.open_tunnel( + transport, data["port"], known_hosts, excluded_ports=used_ports, + ) base = f"http://127.0.0.1:{tunnel.port}" try: - async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client: + async with httpx.AsyncClient(timeout=20, trust_env=False, follow_redirects=False) as client: response = await client.get( f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]}, ) @@ -218,28 +404,58 @@ class RemoteInstances: if not isinstance(raw_identity, dict): raise RemoteError("incompatible_gateway") identity = cast(dict[str, Any], raw_identity) - if (identity.get("protocolVersion") != 1 + if (type(identity.get("protocolVersion")) is not int or 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") + # SSH aliases identify routes, not nanobot instances. Don't open + # two independent browser views of the same live gateway. + if any(item.gateway_id == identity["gatewayId"] + for item in self.connections.values()): + raise RemoteError("duplicate_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") + issue_path = data.get("token_issue_path", "") + if not isinstance(issue_path, str): + raise RemoteError("incompatible_gateway") + if proxy is None: + proxy = await RemoteProxy.open( + tunnel, data["secret"], identity["gatewayId"], issue_path, + local_port=local_port, excluded_ports=used_ports, + ) + else: + proxy.resume(data["secret"], identity["gatewayId"], issue_path) connection = Connection( tunnel, data["secret"], str(data.get("hostname", profile.host)), - str(data.get("config_path", profile.config_path)), identity["gatewayId"], + str(data.get("config_path", profile.config_path)), identity["gatewayId"], proxy, + paired=bool(profile.pair_id), ) profiles = self._read() - profiles[key].local_port = tunnel.port + self._remember_origins(profiles, proxy.port) + profiles[key].local_port = proxy.port + profiles[key].proxy_origin = True self._write(profiles) + self._proxies[proxy.port] = proxy self.connections[key] = connection return self._launch(key, profile, connection) except BaseException as exc: - await tunnel.close() + if proxy is not None and proxy.port in self._proxies: + await proxy.pause() + else: + # No launch URL has been returned for this new origin. All + # internal HTTP requests have finished; retaining it would leak + # a listener on every failed attempt with local_port still zero. + if proxy is not None: + await proxy.close() + else: + await tunnel.close() if isinstance(exc, httpx.HTTPError): - raise RemoteError("remote_unreachable") from None + if profile.pair_id and tunnel.error == "ssh_auth_failed": + raise RemoteError("pair_authorization_rejected") from None + raise RemoteError(tunnel.error or "remote_unreachable") from None if isinstance(exc, ValueError): raise RemoteError("incompatible_gateway") from None raise @@ -247,5 +463,6 @@ class RemoteInstances: 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())) + proxies, self._proxies = self._proxies, {} + self.connections.clear() + await asyncio.gather(*(proxy.close() for proxy in proxies.values())) diff --git a/nanobot/webui/remote_pair_server.py b/nanobot/webui/remote_pair_server.py new file mode 100644 index 000000000..ec8193b1f --- /dev/null +++ b/nanobot/webui/remote_pair_server.py @@ -0,0 +1,213 @@ +"""Explicit server-side authorization for relay-free remote WebUI pairing. + +Only an already-authorized server operator runs this module. No daemon, sudoers +rule, listener or SSH policy is installed. The dedicated key executes one fixed +stdio bridge, with all OpenSSH forwarding and interactive features disabled. +""" + +from __future__ import annotations + +import datetime +import fcntl +import json +import os +import shlex +import socket +import stat +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write, public_key, seal +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 +s = socket.create_connection(("127.0.0.1", PORT), timeout=10) +s.settimeout(None) +def send(): + try: + while True: + data = os.read(0, 65536) + if not data: + break + s.sendall(data) + s.shutdown(socket.SHUT_WR) + except OSError: + s.close() +threading.Thread(target=send, daemon=True).start() +try: + while True: + data = s.recv(65536) + if not data: + break + while data: + data = data[os.write(1, data):] +finally: + s.close() +''' + + +def metadata(config: Path) -> dict[str, Any]: + """Read only the WebUI credential out of the operator-selected config.""" + try: + raw = json.loads(config.read_text()) + ws = raw.get("channels", {}).get("websocket", {}) + secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token") + if not ws.get("enabled") or not isinstance(secret, str) or not secret.strip() or "${" in secret: + raise RemoteError("webui_auth_required") + if ws.get("publicWsUrl") or ws.get("public_ws_url") or ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"): + raise RemoteError("incompatible_gateway") + port = ws.get("port", 8765) + if type(port) is not int or not 1 <= port <= 65535: + raise ValueError + return {"port": port, "secret": secret, "hostname": socket.gethostname(), + "config_path": str(config.resolve()), + "token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or ""} + except PermissionError: + raise RemoteError("config_permission") from None + except (OSError, ValueError, TypeError, AttributeError): + raise RemoteError("config_invalid") from None + + +def _directory(path: Path) -> None: + if path.is_symlink(): + raise RemoteError("pair_ssh_layout") + path.mkdir(mode=0o700, exist_ok=True) + info = path.stat() + if info.st_uid != os.getuid() or info.st_mode & 0o022: + raise RemoteError("pair_ssh_layout") + + +def write_authorization(home: Path, request: PairRequest, port: int, until: int) -> None: + """Runs as the SSH account, never with root privileges over another home.""" + request.check_expiry() + ssh = home / ".ssh" + _directory(ssh) + root = ssh / "nanobot-remote" + _directory(root) + target = root / request.id + # Only our lock file; do not change permissions/content of unrelated keys. + lock = os.open(root / "lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + with os.fdopen(lock, "r+") as guard: + fcntl.flock(guard, fcntl.LOCK_EX) + if target.exists(): + raise RemoteError("pair_used") + target.mkdir(mode=0o700) + try: + bridge = target / "bridge.py" + private_write(bridge, _BRIDGE.replace("PORT", str(port)).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' + private_write(target / "authorization", line.encode()) + _update_keys(ssh / "authorized_keys", add=line) + except BaseException: + # Never remove an existing directory or unrelated key on rollback. + for name in ("bridge.py", "authorization"): + (target / name).unlink(missing_ok=True) + target.rmdir() + raise + + +def _update_keys(path: Path, *, add: str = "", remove: str = "") -> None: + fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "r+") as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_nlink != 1 or info.st_mode & 0o022: + raise RemoteError("pair_ssh_layout") + fcntl.flock(handle, fcntl.LOCK_EX) + original = handle.read(1024 * 1024 + 1) + if len(original) > 1024 * 1024: + raise RemoteError("pair_ssh_layout") + if add: + handle.seek(0, 2) + handle.write(("\n" if original and not original.endswith("\n") else "") + add) + else: + # Exact managed line, not a substring/comment match. + replacement = "".join(line for line in original.splitlines(keepends=True) if line != remove) + if replacement == original: + return + temporary_fd, temporary_name = tempfile.mkstemp(prefix=".nanobot-revoke-", dir=path.parent) + try: + with os.fdopen(temporary_fd, "w") as output: + output.write(replacement) + output.flush() + os.fsync(output.fileno()) + os.fchmod(output.fileno(), stat.S_IMODE(info.st_mode)) + os.replace(temporary_name, path) + finally: + Path(temporary_name).unlink(missing_ok=True) + handle.flush() + os.fsync(handle.fileno()) + + +def remove_authorization(home: Path, key: str) -> None: + from nanobot.webui.remote_pairing import PairStore + + # Validate before joining any path, even for a manually typed revoke command. + PairStore(home).path(key) + root = home / ".ssh" / "nanobot-remote" + _directory(home / ".ssh") + _directory(root) + target = root / key + if target.is_symlink() or not target.is_dir(): + raise RemoteError("pair_invalid") + lock = os.open(root / "lock", os.O_RDWR | os.O_NOFOLLOW) + with os.fdopen(lock, "r+") as guard: + fcntl.flock(guard, fcntl.LOCK_EX) + line = (target / "authorization").read_text() + if not line.endswith(f" nanobot-remote:{key}\n") or "\n" in line[:-1]: + raise RemoteError("pair_invalid") + _update_keys(home / ".ssh/authorized_keys", remove=line) + # Keep the non-secret receipt/bridge for an auditable, retryable revoke. + + +def as_account(user: str, operation: str, data: dict[str, Any]) -> None: + import pwd + + account = pwd.getpwnam(user) + if account.pw_uid == 0 or account.pw_shell.endswith(("/nologin", "/false")): + raise RemoteError("pair_login_user") + if os.getuid() not in (0, account.pw_uid): + raise RemoteError("config_permission") + child = dict(data, home=account.pw_dir, operation=operation) + # Drop all supplementary groups *before* any write in a user-owned home. + options: dict[str, Any] = {} + if os.getuid() == 0: + options = {"user": account.pw_uid, "group": account.pw_gid, "extra_groups": []} + result = subprocess.run( + [sys.executable, "-m", "nanobot.webui.remote_pair_server"], + input=json.dumps(child), text=True, capture_output=True, timeout=20, **options, + ) + if result.returncode: + code = result.stdout.strip() + raise RemoteError(code if code in {"pair_used", "pair_expired", "pair_ssh_layout", "pair_invalid"} else "pair_install_failed") + + +def authorize(request: PairRequest, *, host: str, user: str, ssh_port: int, + config: Path, host_key: str, until: int) -> str: + request.check_expiry() + receipt = PairReceipt(id=request.id, ssh_key=request.ssh_key, host=host, user=user, + ssh_port=ssh_port, host_key=public_key(host_key), authorized_until=until, + **metadata(config)) + encrypted = seal(request, receipt) # Fail crypto/validation before authorizing anything. + as_account(user, "install", {"request": request.model_dump(), "port": receipt.port, "until": until}) + return encrypted + + +if __name__ == "__main__": + try: + data = json.loads(sys.stdin.read(32768)) + if data["operation"] == "install": + write_authorization(Path(data["home"]), PairRequest.model_validate(data["request"]), data["port"], data["until"]) + elif data["operation"] == "revoke": + remove_authorization(Path(data["home"]), data["id"]) + else: + raise RemoteError("pair_invalid") + except Exception as exc: + print(str(exc) if isinstance(exc, RemoteError) else "pair_install_failed") + sys.exit(1) diff --git a/nanobot/webui/remote_pairing.py b/nanobot/webui/remote_pairing.py new file mode 100644 index 000000000..87888248c --- /dev/null +++ b/nanobot/webui/remote_pairing.py @@ -0,0 +1,322 @@ +"""Copy/paste pairing protocol. Private material never enters the WebUI response. + +The request is public. A receipt is encrypted for the requesting local instance; +its provenance is the user's trusted server terminal, not a public relay. SSH's +host key is pinned from that receipt before any credential-bearing connection. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +import os +import re +import secrets +import socket +import time +import uuid +from pathlib import Path +from typing import Any, cast + +from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ed25519, x25519 +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF +from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator + +from nanobot.webui.remote_ssh import RemoteError, RemoteProfile + +_TTL = 600 +_CONTEXT = b"nanobot-remote-pair-v1" + + +def local_return_origin(value: str) -> str: + """Only the local top-level WebUI can receive a pairing link. No redirects.""" + if value == "": + return value + match = re.fullmatch(r"http://(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]{1,5}))?", value) + if not match or (match[2] is not None and not 1 <= int(match[2]) <= 65535): + raise ValueError("local return address required") + return value + + +def return_link(request: PairRequest, code: str) -> str: + # Fragment data is never sent in the HTTP request or Referer. The frontend + # scrubs it before authentication and still requires a confirmation. + if not request.return_origin: + return "" + if not re.fullmatch(r"nbpc1\.[A-Za-z0-9_-]{1,32762}", code): + raise RemoteError("pair_invalid") + return f"{local_return_origin(request.return_origin)}/#/remote?pairing={code}" + + +def encode(value: bytes) -> str: + return base64.urlsafe_b64encode(value).decode().rstrip("=") + + +def decode(value: str) -> bytes: + return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True) + + +def pack(prefix: str, data: dict[str, Any]) -> str: + return prefix + encode(json.dumps(data, separators=(",", ":")).encode()) + + +def unpack(prefix: str, value: str) -> dict[str, Any]: + if len(value) > 32768: + raise RemoteError("pair_invalid") + value = "".join(value.split()) + try: + if not value.startswith(prefix): + raise ValueError + raw = json.loads(decode(value[len(prefix):])) + if not isinstance(raw, dict): + raise ValueError + return cast(dict[str, Any], raw) + except (ValueError, TypeError, UnicodeError): + raise RemoteError("pair_invalid") from None + + +def public_key(value: str) -> str: + """Accept exactly one Ed25519 key, without options, comments or newlines.""" + try: + key = serialization.load_ssh_public_key(value.encode()) + except UnsupportedAlgorithm: + raise ValueError("Ed25519 required") from None + if not isinstance(key, ed25519.Ed25519PublicKey): + raise ValueError("Ed25519 required") + canonical = key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode() + if canonical != value: + raise ValueError("non-canonical key") + return value + + +def fingerprint(key: str) -> str: + return "SHA256:" + base64.b64encode(hashlib.sha256(base64.b64decode(key.split()[1])).digest()).decode().rstrip("=") + + +class PairRequest(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + id: str + expires: int + label: str = Field(min_length=1, max_length=64, pattern=r"^[\w .@-]+$") + ssh_key: str = Field(max_length=256) + exchange_key: str = Field(min_length=43, max_length=43) + return_origin: str = Field(default="", max_length=64) + + @field_validator("return_origin") + @classmethod + def valid_return_origin(cls, value: str) -> str: + return local_return_origin(value) + + @field_validator("id") + @classmethod + def valid_id(cls, value: str) -> str: + if str(uuid.UUID(value)) != value: + raise ValueError("invalid id") + return value + + @field_validator("ssh_key") + @classmethod + def valid_key(cls, value: str) -> str: + return public_key(value) + + @field_validator("exchange_key") + @classmethod + def valid_exchange(cls, value: str) -> str: + x25519.X25519PublicKey.from_public_bytes(decode(value)) + return value + + def check_expiry(self) -> None: + if not time.time() < self.expires <= time.time() + _TTL + 60: + raise RemoteError("pair_expired") + + +def read_request(value: str) -> PairRequest: + try: + request = PairRequest.model_validate(unpack("nbpr1.", value)) + request.check_expiry() + return request + except (ValidationError, ValueError): + raise RemoteError("pair_invalid") from None + + +class PairReceipt(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True) + id: str + ssh_key: str + host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9.:-]*$") + user: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z_][a-zA-Z0-9_-]*$") + ssh_port: int = Field(ge=1, le=65535) + host_key: str + hostname: str = Field(min_length=1, max_length=253) + config_path: str = Field(min_length=1, max_length=2048) + port: int = Field(ge=1, le=65535) + secret: str = Field(min_length=1, max_length=4096, repr=False) + token_issue_path: str = Field(default="", max_length=2048) + authorized_until: int + + @field_validator("host_key", "ssh_key") + @classmethod + def valid_key(cls, value: str) -> str: + return public_key(value) + + def preview(self) -> dict[str, Any]: + return {"id": self.id, "host": f"{self.user}@{self.host}", "port": self.ssh_port, + "hostname": self.hostname, "fingerprint": fingerprint(self.host_key), + "authorized_until": self.authorized_until, + "revoke_command": f"nanobot remote revoke {self.id} --ssh-user {self.user}"} + + +def _derive(shared: bytes, request_id: str) -> bytes: + return HKDF(algorithm=hashes.SHA256(), length=32, salt=request_id.encode(), info=_CONTEXT).derive(shared) + + +def seal(request: PairRequest, receipt: PairReceipt) -> str: + private = x25519.X25519PrivateKey.generate() + peer = x25519.X25519PublicKey.from_public_bytes(decode(request.exchange_key)) + nonce = secrets.token_bytes(12) + encrypted = AESGCM(_derive(private.exchange(peer), request.id)).encrypt( + nonce, receipt.model_dump_json().encode(), _CONTEXT + request.id.encode(), + ) + return pack("nbpc1.", {"id": request.id, "key": encode(private.public_key().public_bytes_raw()), + "nonce": encode(nonce), "data": encode(encrypted)}) + + +def private_write(path: Path, content: bytes) -> None: + # Callers own the private parent directory. Never overwrite or follow links. + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + + +class PairStore: + def __init__(self, directory: Path) -> None: + self.root = directory / "remote-pairing" + + def path(self, key: str) -> Path: + try: + if str(uuid.UUID(key)) != key: + raise ValueError + except (ValueError, AttributeError): + raise RemoteError("pair_invalid") from None + return self.root / key + + def start(self, return_origin: str = "") -> dict[str, Any]: + try: + return_origin = local_return_origin(return_origin) + except (ValueError, TypeError): + raise RemoteError("pair_invalid") from None + self.root.mkdir(mode=0o700, parents=True, exist_ok=True) + if self.root.is_symlink(): + raise RemoteError("local_io_error") + self.root.chmod(0o700) + # Bound abandoned requests without deleting completed device identities. + pending = 0 + for path in self.root.iterdir(): + if path.is_dir() and not (path / "receipt").exists(): + if path.stat().st_mtime < time.time() - _TTL: + self.cancel(path.name) + else: + pending += 1 + if pending >= 8: + raise RemoteError("pair_limit") + key = str(uuid.uuid4()) + path = self.path(key) + path.mkdir(mode=0o700) + ssh = ed25519.Ed25519PrivateKey.generate() + exchange = x25519.X25519PrivateKey.generate() + request = PairRequest(id=key, expires=int(time.time()) + _TTL, + label="".join(c for c in socket.gethostname() if c.isalnum() or c in ".-_")[:64] or "Computer", + ssh_key=ssh.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode(), + exchange_key=encode(exchange.public_key().public_bytes_raw()), + return_origin=return_origin) + private_write(path / "identity", ssh.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption())) + private_write(path / "exchange", exchange.private_bytes_raw()) + private_write(path / "request", request.model_dump_json().encode()) + return {"id": key, "expires": request.expires, + "command": "nanobot remote pair " + pack("nbpr1.", request.model_dump(exclude_defaults=True))} + + def _decrypt(self, key: str, code: str, *, pending: bool, require_active: bool = True) -> PairReceipt: + path = self.path(key) + try: + request = PairRequest.model_validate_json((path / "request").read_bytes()) + if pending: + request.check_expiry() + envelope = unpack("nbpc1.", code) + if envelope.get("id") != key: + raise ValueError + private = x25519.X25519PrivateKey.from_private_bytes((path / "exchange").read_bytes()) + peer = x25519.X25519PublicKey.from_public_bytes(decode(envelope["key"])) + clear = AESGCM(_derive(private.exchange(peer), key)).decrypt( + decode(envelope["nonce"]), decode(envelope["data"]), _CONTEXT + key.encode(), + ) + receipt = PairReceipt.model_validate_json(clear) + if receipt.id != key or receipt.ssh_key != request.ssh_key: + raise ValueError + if require_active and receipt.authorized_until <= time.time(): + raise RemoteError("pair_authorization_expired") + return receipt + except (OSError, ValueError, TypeError, KeyError, InvalidTag): + raise RemoteError("pair_invalid") from None + + def preview(self, key: str, code: str) -> dict[str, Any]: + return self._decrypt(key, code, pending=True).preview() + + def finish(self, key: str, code: str) -> PairReceipt: + receipt = self._decrypt(key, code, pending=True) + path = self.path(key) / "receipt" + if path.exists(): + if path.read_text() != code: + raise RemoteError("pair_used") + else: + private_write(path, code.encode()) + return receipt + + def connection(self, key: str) -> dict[str, Any]: + try: + code = (self.path(key) / "receipt").read_text() + except OSError: + raise RemoteError("pair_invalid") from None + return self._decrypt(key, code, pending=False).model_dump() + + def authorization_until(self, key: str) -> int | None: + """Expose only the expiry for display, including already-expired grants. + + Connecting still goes through connection(), which rejects expired grants. + A missing/unreadable receipt must not hide every other saved server. + """ + try: + code = (self.path(key) / "receipt").read_text() + return self._decrypt(key, code, pending=False, require_active=False).authorized_until + except (OSError, RemoteError): + return None + + def cancel(self, key: str) -> None: + path = self.path(key) + if path.is_symlink() or (path / "receipt").exists(): + return + for name in ("identity", "exchange", "request"): + (path / name).unlink(missing_ok=True) + if path.exists(): + path.rmdir() + + def forget(self, key: str) -> None: + """Destroy only this managed local identity; server revocation is separate.""" + path = self.path(key) + if path.is_symlink(): + raise RemoteError("local_io_error") + for name in ("identity", "exchange", "request", "receipt", "ssh_route"): + (path / name).unlink(missing_ok=True) + if path.exists(): + path.rmdir() + + def profile(self, receipt: PairReceipt, ssh_config: str = "") -> RemoteProfile: + return RemoteProfile(name=receipt.hostname[:64], host=f"{receipt.user}@{receipt.host}", + port=receipt.ssh_port, config_path=receipt.config_path, + identity_file=str(self.path(receipt.id) / "identity"), + ssh_config=ssh_config) diff --git a/nanobot/webui/remote_proxy.py b/nanobot/webui/remote_proxy.py new file mode 100644 index 000000000..fec3cc997 --- /dev/null +++ b/nanobot/webui/remote_proxy.py @@ -0,0 +1,368 @@ +"""A browser origin with local capabilities, not reusable remote credentials. + +The private SSH listener is never published. This proxy drains its requests +before releasing that listener; a process reclaiming the public browser port +after shutdown can receive only capabilities from an already-dead proxy. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import json +import math +import re +import secrets +import socket +import time +from collections import OrderedDict +from dataclasses import dataclass +from typing import Any, cast + +import httpx +from aiohttp import WSMsgType, web +from cryptography.fernet import Fernet, InvalidToken +from websockets.asyncio.client import connect +from websockets.exceptions import WebSocketException +from websockets.typing import Origin +from yarl import URL + +from nanobot.webui.remote_ssh import Tunnel, _listen # pyright: ignore[reportPrivateUsage] + +_MAX_BYTES = 64 * 1024 * 1024 +_MAX_CAPABILITIES = 10000 +_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. +_MEDIA = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*:)?//[^\s<>\"'`()]+|" + rf"(?{_MEDIA_PATH})") +_REQUEST_HEADERS = {"accept", "accept-language", "content-type", "range", "if-range"} +_RESPONSE_HEADERS = { + "content-type", "content-range", "accept-ranges", "content-disposition", + "content-security-policy", "x-content-type-options", "last-modified", +} + + +@dataclass(frozen=True) +class _Grant: + remote: str + expires: float + path: str = "" + + +class RemoteProxy: + """Owns the public listener, local credentials and a private SSH transport.""" + + def __init__(self, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str) -> None: + self.tunnel = tunnel + self.secret = secrets.token_urlsafe(32) + self.port = 0 + self._remote_secret = secret + self._gateway_id = gateway_id + self._issue_path = issue_path.rstrip("/") or "" + # Reload caches are scoped to WS pathname. A fresh process must not + # reuse cached transcripts containing a previous proxy's media grants. + self._ws_path = "/remote-session/" + secrets.token_urlsafe(18) + self._api: dict[str, _Grant] = {} + self._ws: dict[str, _Grant] = {} + self._media_cipher = Fernet(Fernet.generate_key()) + self._media_cache: OrderedDict[str, str] = OrderedDict() + self._tasks: set[asyncio.Task[Any]] = set() + self._bootstrap_lock = asyncio.Lock() + self._enabled = True + self._runner: web.AppRunner | None = None + + @classmethod + async def open( + cls, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str = "", + *, local_port: int = 0, excluded_ports: set[int] | None = None, + ) -> RemoteProxy: + self = cls(tunnel, secret, gateway_id, issue_path) + listener = _listen(local_port, excluded_ports or set()) + self.port = int(listener.getsockname()[1]) + app = web.Application(client_max_size=_MAX_BYTES) + app.router.add_route("*", "/{path:.*}", self._handle) + self._runner = web.AppRunner(app, access_log=None, handler_cancellation=True) + try: + await self._runner.setup() + await web.SockSite(self._runner, listener).start() + return self + except BaseException: + listener.close() + await self._runner.cleanup() + raise + + @property + def active(self) -> bool: + return self._enabled and self.tunnel.active + + @property + def origin(self) -> str: + return f"http://127.0.0.1:{self.port}" + + def resume(self, secret: str, gateway_id: str, issue_path: str = "") -> None: + if gateway_id != self._gateway_id: + self._ws_path = "/remote-session/" + secrets.token_urlsafe(18) + self._api.clear() + self._ws.clear() + self._media_cipher = Fernet(Fernet.generate_key()) + self._media_cache.clear() + self._remote_secret = secret + self._gateway_id = gateway_id + self._issue_path = issue_path.rstrip("/") or "" + self._enabled = True + + async def pause(self) -> None: + self._enabled = False + tasks = list(self._tasks) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + self._api.clear() + self._ws.clear() + await self.tunnel.pause() + + async def close(self) -> None: + await self.pause() + if self._runner is not None: + await self._runner.cleanup() + self._runner = None + self._remote_secret = "" + self._media_cipher = Fernet(Fernet.generate_key()) + self._media_cache.clear() + await self.tunnel.close() + + def _credential(self, request: web.Request, *, bootstrap: bool = False) -> str: + # Decode query names once. Reject duplicates and mixed aliases rather + # than allowing the client and upstream to disagree about precedence. + auth = request.headers.getall("Authorization", []) + issue = request.headers.getall("X-Nanobot-Auth", []) + query = request.rel_url.query.getall("token", []) + if len(auth) + len(issue) + len(query) > 1: + raise web.HTTPUnauthorized() + if auth: + scheme, _, value = auth[0].partition(" ") + if scheme.lower() != "bearer" or not value: + raise web.HTTPUnauthorized() + return value + if bootstrap and issue: + return issue[0] + if not bootstrap and query: + return query[0] + return "" + + def _grant(self, token: str, grants: dict[str, _Grant], *, consume: bool = False) -> _Grant: + grant = grants.pop(token, None) if consume else grants.get(token) + if grant is None or grant.expires <= time.monotonic(): + raise web.HTTPUnauthorized() + return grant + + async def _handle(self, request: web.Request) -> web.StreamResponse: + if (request.headers.getall("Host", []) != [f"127.0.0.1:{self.port}"] + or request.headers.getall("Origin", []) not in ([], [self.origin])): + raise web.HTTPForbidden() + if not self.active: + raise web.HTTPServiceUnavailable() + task = asyncio.current_task() + assert task is not None + self._tasks.add(task) + try: + # The upstream gateway uses the raw path (not unquoted path) for + # routing. Keep it intact and do not normalize escaped separators. + path = request.rel_url.raw_path.rstrip("/") or "/" + if path == self._issue_path: + raise web.HTTPForbidden() + if request.headers.get("Upgrade", "").lower() == "websocket": + if path != self._ws_path: + raise web.HTTPNotFound() + grant = self._grant(self._credential(request), self._ws, consume=True) + return await self._websocket(request, grant) + if path == "/webui/bootstrap": + if request.method != "GET": + raise web.HTTPMethodNotAllowed(request.method, ["GET"]) + supplied = self._credential(request, bootstrap=True) + if not secrets.compare_digest(supplied.encode(), self.secret.encode()): + raise web.HTTPUnauthorized() + async with self._bootstrap_lock: + return await self._bootstrap() + if path == "/webui/terminal": + raise web.HTTPForbidden() + return await self._http(request, path) + except (httpx.HTTPError, WebSocketException, OSError, ValueError): + # Never reflect upstream URLs, credentials or raw exception text. + raise web.HTTPBadGateway(text="Remote connection unavailable") from None + finally: + self._tasks.discard(task) + + def _headers(self, request: web.Request) -> dict[str, str]: + headers = {key: value for key, value in request.headers.items() + if key.lower() in _REQUEST_HEADERS} + headers["Host"] = f"127.0.0.1:{self.port}" + headers["Origin"] = self.origin + return headers + + def _upstream(self, path: str) -> str: + return f"http://127.0.0.1:{self.tunnel.port}{path}" + + async def _bootstrap(self) -> web.Response: + now = time.monotonic() + for grants in (self._api, self._ws): + for key in [key for key, value in grants.items() if value.expires <= now]: + del grants[key] + if len(grants) >= _MAX_CAPABILITIES: + raise web.HTTPTooManyRequests() + async with httpx.AsyncClient(trust_env=False, timeout=20) as client: + response = await client.get(self._upstream("/webui/bootstrap"), headers={ + "X-Nanobot-Auth": self._remote_secret, "Host": f"127.0.0.1:{self.port}", + }) + if response.status_code != 200: + raise web.HTTPBadGateway(text="Remote authentication unavailable") + payload: object = response.json() + if not isinstance(payload, dict): + raise ValueError("invalid bootstrap") + data = cast(dict[str, Any], payload) + terminal = data.get("terminal") + if not isinstance(terminal, dict): + raise ValueError("invalid terminal") + terminal = cast(dict[str, Any], terminal) + ttl, ws_path = data.get("expires_in"), data.get("ws_path") + if (terminal.get("gatewayId") != self._gateway_id + or terminal.get("protocolVersion") != 1 + or not isinstance(ttl, (float, int)) or not math.isfinite(ttl) or not 0 < ttl <= 86400 + or not isinstance(ws_path, str) or not ws_path.startswith("/") + or ws_path.startswith("//") or "?" in ws_path or "#" in ws_path + or any(ord(c) < 33 for c in ws_path) + or not isinstance(data.get("token"), str) or not data["token"] + or not isinstance(data.get("api_token"), str) or not data["api_token"]): + raise ValueError("incompatible bootstrap") + token, api_token = secrets.token_urlsafe(32), secrets.token_urlsafe(32) + # Count elapsed upstream time against the remote token's TTL. + self._ws[token] = _Grant(data["token"], now + ttl, ws_path) + self._api[api_token] = _Grant(data["api_token"], now + ttl) + result = {key: data[key] for key in ( + "limits", "model_name", "runtime_surface", "runtime_capabilities", + ) if key in data} + result.update(token=token, api_token=api_token, expires_in=ttl, + terminal={"protocolVersion": 1, "gatewayId": self._gateway_id}, + ws_path=self._ws_path, ws_url=f"ws://127.0.0.1:{self.port}{self._ws_path}") + return web.json_response(result, headers={"Cache-Control": "no-store"}) + + def _local_media(self, match: re.Match[str]) -> str: + remote = match.group("media") + if remote is None: + return match.group() + existing = self._media_cache.get(remote) + if existing: + self._media_cache.move_to_end(remote) + return existing + # Authenticated encryption hides the remote bearer URL without retaining + # an unbounded mapping. Eviction only changes future URL spelling: every + # previously issued URL still works for this proxy's lifetime. + local = "/api/media/local/" + self._media_cipher.encrypt(remote.encode()).decode() + if len(self._media_cache) >= _MAX_CAPABILITIES: + self._media_cache.popitem(last=False) + self._media_cache[remote] = local + return local + + def _remote_media(self, path: str) -> str: + prefix = "/api/media/local/" + if not path.startswith(prefix): + raise web.HTTPUnauthorized() + try: + remote = self._media_cipher.decrypt(path[len(prefix):].encode()).decode() + except (InvalidToken, UnicodeError, ValueError): + raise web.HTTPUnauthorized() from None + if not re.fullmatch(_MEDIA_PATH, remote): + raise web.HTTPUnauthorized() + return remote + + def _rewrite(self, value: Any) -> Any: + if isinstance(value, str): + return _MEDIA.sub(self._local_media, value) + if isinstance(value, list): + return [self._rewrite(item) for item in cast(list[Any], value)] + if isinstance(value, dict): + return {key: self._rewrite(item) for key, item in cast(dict[str, Any], value).items()} + return value + + async def _http(self, request: web.Request, path: str) -> web.StreamResponse: + url = request.rel_url.with_query([ + (key, value) for key, value in request.rel_url.query.items() if key != "token" + ]) + headers = self._headers(request) + if path.startswith("/api/media/"): + remote = self._remote_media(path) + url = URL(remote).with_query(url.query) + elif path.startswith("/api/"): + grant = self._grant(self._credential(request), self._api) + headers["Authorization"] = "Bearer " + grant.remote + # HTTP API and static responses are read-only. WebUI writes travel over + # its authenticated multiplex WebSocket, not an arbitrary HTTP relay. + if request.method not in {"GET", "HEAD"}: + raise web.HTTPMethodNotAllowed(request.method, ["GET", "HEAD"]) + async with httpx.AsyncClient(trust_env=False, timeout=30) as client: + async with client.stream(request.method, self._upstream(str(url)), headers=headers) as upstream: + if upstream.is_redirect: + raise web.HTTPBadGateway(text="Unexpected remote redirect") + outgoing = {key: value for key, value in upstream.headers.items() + if key.lower() in _RESPONSE_HEADERS} + outgoing["Cache-Control"] = "no-store" + if "application/json" in upstream.headers.get("content-type", ""): + body = bytearray() + async for chunk in upstream.aiter_bytes(): + body.extend(chunk) + if len(body) > _MAX_BYTES: + raise ValueError("response too large") + if request.method == "HEAD": + return web.Response(status=upstream.status_code, headers=outgoing) + return web.Response(body=json.dumps(self._rewrite(json.loads(body))).encode(), + status=upstream.status_code, headers=outgoing) + result = web.StreamResponse(status=upstream.status_code, headers=outgoing) + await result.prepare(request) + async for chunk in upstream.aiter_bytes(): + await result.write(chunk) + await result.write_eof() + return result + + async def _websocket(self, request: web.Request, grant: _Grant) -> web.WebSocketResponse: + # An already-connected socket fixes the upstream and disables all WS + # redirects. Its HTTP authority still matches the browser's origin. + upstream_socket = socket.socket() + upstream_socket.setblocking(False) + try: + await asyncio.wait_for(asyncio.get_running_loop().sock_connect( + upstream_socket, ("127.0.0.1", self.tunnel.port), + ), 20) + query = [(key, value) for key, value in request.rel_url.query.items() if key != "token"] + query.append(("token", grant.remote)) + url = URL(f"ws://127.0.0.1:{self.port}").with_path(grant.path, encoded=True).with_query(query) + async with connect(str(url), sock=upstream_socket, proxy=None, origin=Origin(self.origin), + max_size=_MAX_BYTES, open_timeout=20, close_timeout=2) as upstream: + browser = web.WebSocketResponse(max_msg_size=_MAX_BYTES, heartbeat=30) + await browser.prepare(request) + + async def receive() -> None: + try: + async for message in upstream: + if isinstance(message, bytes): + await browser.send_bytes(message) + else: + await browser.send_str(json.dumps(self._rewrite(json.loads(message)))) + finally: + await browser.close() + + reader = asyncio.create_task(receive()) + try: + async for message in browser: + if message.type in {WSMsgType.TEXT, WSMsgType.BINARY}: + await upstream.send(message.data) + finally: + reader.cancel() + await asyncio.gather(reader, return_exceptions=True) + await browser.close() + return browser + finally: + # connect owns the socket after handoff; close is also safe if + # cancellation occurred before the protocol took ownership. + with contextlib.suppress(OSError): + upstream_socket.close() diff --git a/nanobot/webui/remote_ssh.py b/nanobot/webui/remote_ssh.py index 7f7817308..207e92ec9 100644 --- a/nanobot/webui/remote_ssh.py +++ b/nanobot/webui/remote_ssh.py @@ -8,12 +8,13 @@ from __future__ import annotations import asyncio import base64 +import contextlib import hashlib import json +import os import shlex import shutil import socket -from dataclasses import dataclass from pathlib import Path from typing import Any, cast @@ -43,9 +44,27 @@ class RemoteProfile(BaseModel): return value +class PairedSSHProfile(RemoteProfile): + """Internal transport marker. Not accepted by the editable profile API.""" + + +def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: Path | None) -> list[str]: + args = ssh_arguments(profile, known_hosts) + 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, "-W", f"127.0.0.1:{remote_port}", profile.host] + + +# Frame the result so login banners don't get mistaken for invalid config JSON. +_PROBE_PREFIX = b"\x1eNANOBOT_REMOTE:" + # Fixed program, quoted as one shell argument. No user-supplied shell commands. _PROBE = r''' import json, os, pathlib, socket, sys +def emit(value): + print("\n\x1eNANOBOT_REMOTE:" + json.dumps(value)) try: path = pathlib.Path(sys.argv[1]).expanduser() data = json.loads(path.read_text()) @@ -57,15 +76,20 @@ try: 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)})) + if ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"): + raise ValueError("incompatible_gateway") + emit({"port": ws.get("port", 8765), "secret": secret, + "token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or "", + "hostname": socket.gethostname(), "config_path": str(path)}) except FileNotFoundError: - print(json.dumps({"error": "config_not_found"})) + emit({"error": "config_not_found"}) except PermissionError: - print(json.dumps({"error": "config_permission"})) + emit({"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"})) + emit({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported", "incompatible_gateway"} else "config_invalid"}) +except (AttributeError, TypeError): + emit({"error": "config_invalid"}) ''' @@ -74,6 +98,8 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> li if not executable: raise RemoteError("ssh_unavailable") args = [executable] + if isinstance(profile, PairedSSHProfile) and not profile.ssh_config: + args.extend(["-F", os.devnull]) for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]: if value: path = Path(value).expanduser() @@ -88,9 +114,19 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> li "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2", "-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no", + # Interactive aliases may start tmux or another shell automatically. + # This connection runs only our fixed probe and forwarding transport. + # Older clients lack these settings and the corresponding behavior. + "-o", "IgnoreUnknown=StdinNull,ForkAfterAuthentication,RemoteCommand", + "-o", "RemoteCommand=none", + "-o", "ClearAllForwardings=yes", "-o", "StdinNull=no", + "-o", "ForkAfterAuthentication=no", ]) if profile.port is not None: args.extend(["-p", str(profile.port)]) + if isinstance(profile, PairedSSHProfile): + # Never fall back to a user's unrelated identity or agent for this grant. + args.extend(["-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none"]) 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", @@ -104,10 +140,28 @@ def ssh_error(stderr: bytes) -> str: 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 "unprotected private key file" in text or "bad permissions" in text: + return "ssh_key_permissions" + if "agent refused operation" in text or "signing failed" in text: + return "ssh_agent_refused" + if "bad configuration option" in text or "terminating, 1 bad configuration" in text: + return "ssh_config_invalid" + if "administratively prohibited" in text: + return "ssh_forwarding_denied" + if "open failed: connect failed" in text: + return "remote_unreachable" + if "too many authentication failures" in text: + return "ssh_too_many_keys" + if "permission denied" in text: + return "ssh_auth_failed" + if "connection refused" in text: + return "ssh_refused" + if "could not resolve hostname" in text: + return "ssh_host_not_found" + if "connection closed" in text or "connection reset" in text: + return "ssh_connection_closed" if "python3" in text and "not found" in text: return "python_unavailable" return "ssh_unreachable" @@ -129,8 +183,11 @@ async def stop_process(process: asyncio.subprocess.Process) -> None: await process.wait() -async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]: - remote = ["python3", "-c", _PROBE, profile.config_path] +async def run_check( + profile: RemoteProfile, program: str, known_hosts: Path | None = None, +) -> dict[str, Any]: + """Run a fixed read-only program with SSH's existing identity and trust policy.""" + remote = ["python3", "-c", program, profile.config_path] if profile.runtime_user: remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote] process = await asyncio.create_subprocess_exec( @@ -143,73 +200,213 @@ async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict if process.returncode: raise RemoteError(ssh_error(stderr)) try: - raw = json.loads(stdout) + records = [line[len(_PROBE_PREFIX):] for line in stdout.split(b"\n") + if line.startswith(_PROBE_PREFIX)] + if len(records) != 1: + raise ValueError + raw = json.loads(records[0]) 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 + raise RemoteError("probe_failed") from None + except TimeoutError: + raise RemoteError("ssh_unreachable") from None + finally: + await stop_process(process) + + +async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]: + data = await run_check(profile, _PROBE, known_hosts) + if (not isinstance(data.get("secret"), str) or not data["secret"] + or type(data.get("port")) is not int or not 1 <= data["port"] <= 65535): + raise RemoteError("probe_failed") + return data + + +async def pairing_route(source: RemoteProfile, target_host: str) -> str: + """Explicitly reuse a saved route, never its identities or target settings.""" + process = await asyncio.create_subprocess_exec( + *ssh_arguments(source), "-G", source.host, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, + stdin=asyncio.subprocess.DEVNULL, + ) + try: + output, _ = await asyncio.wait_for(process.communicate(), 10) + if process.returncode: + raise RemoteError("ssh_config_invalid") + values = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line) + if values.get("hostname", "").lower() != target_host.lower(): + raise RemoteError("pair_route_mismatch") + if values.get("proxyjump", "none") != "none": + raise RemoteError("pair_route_unsupported") + lines = ["Host *"] + for option in ("proxycommand", "bindaddress", "bindinterface"): + value = values.get(option, "none") + if value != "none": + lines.append(f" {option} {value}") + return "\n".join(lines) + "\n" except TimeoutError: raise RemoteError("ssh_unreachable") from None finally: await stop_process(process) -@dataclass class Tunnel: - process: asyncio.subprocess.Process - port: int + """Own a private loopback transport; upstream bytes only use SSH pipes. + + Pausing closes streams, not the listener: other browser tabs may still retry + that origin. Only final owner shutdown relinquishes the listening socket. + """ + + def __init__(self, args: list[str], port: int) -> None: + self.args = args + self.port = port + self.server: asyncio.Server | None = None + self.enabled = True + self.error = "" + self._streams: set[asyncio.Task[None]] = set() + + @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: + self.args = transport_arguments(profile, remote_port, known_hosts) + self.error = "" + self.enabled = True + + def accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + if not self.active or len(self._streams) >= 32: + writer.close() + return + task = asyncio.create_task(self._relay(reader, writer)) + self._streams.add(task) + + def finished(task: asyncio.Task[None]) -> None: + self._streams.discard(task) + # Cancellation can happen before _relay enters its try/finally. + writer.close() + + task.add_done_callback(finished) + + async def _relay(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + process: asyncio.subprocess.Process | None = None + pumps: list[asyncio.Task[None]] = [] + stderr = bytearray() + + async def copy(source: asyncio.StreamReader, destination: asyncio.StreamWriter) -> None: + while data := await source.read(65536): + destination.write(data) + await destination.drain() + if destination.can_write_eof(): + destination.write_eof() + + async def drain_errors(source: asyncio.StreamReader) -> None: + while data := await source.read(4096): + stderr.extend(data[:max(0, 8192 - len(stderr))]) + + try: + # 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, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, + )) + try: + process = await asyncio.shield(spawn) + except asyncio.CancelledError: + process = await spawn + raise + assert process is not None + assert process.stdin is not None and process.stdout is not None and process.stderr is not None + pumps = [asyncio.create_task(copy(reader, process.stdin)), + asyncio.create_task(copy(process.stdout, writer)), + asyncio.create_task(drain_errors(process.stderr))] + done, _ = await asyncio.wait(pumps[:2], return_when=asyncio.FIRST_COMPLETED) + for task in done: + await task + # Preserve a client's half-close while draining the final response. + # Conversely, EOF from SSH must wake an idle keepalive client. + await pumps[1] + pumps[0].cancel() + process.stdin.close() + await asyncio.wait_for(process.wait(), 3) + await pumps[2] + if process.returncode: + self.error = ssh_error(bytes(stderr)) + except (OSError, ConnectionError): + self.error = "ssh_unreachable" + finally: + for task in pumps: + task.cancel() + await asyncio.gather(*pumps, return_exceptions=True) + if process is not None: + await stop_process(process) + writer.close() + with contextlib.suppress(OSError): + await writer.wait_closed() + + async def pause(self) -> None: + self.enabled = False + streams = list(self._streams) + for task in streams: + task.cancel() + await asyncio.gather(*streams, return_exceptions=True) async def close(self) -> None: - await stop_process(self.process) + await self.pause() + if self.server is not None: + self.server.close() + await self.server.wait_closed() + + +def _listen(local_port: int, excluded_ports: set[int]) -> socket.socket: + # Never release the chosen socket between validation and use. Windows reuse + # has different semantics; exclusive binding rejects existing listeners. + rejected: list[socket.socket] = [] + try: + for _ in range(128): + listener = socket.socket() + try: + if hasattr(socket, "SO_EXCLUSIVEADDRUSE"): + listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + else: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", local_port)) + listener.listen() + if not local_port and listener.getsockname()[1] in excluded_ports: + rejected.append(listener) + continue + listener.setblocking(False) + return listener + except BaseException: + listener.close() + raise + raise RemoteError("local_port_in_use") + except OSError: + raise RemoteError("local_port_in_use") from None + finally: + for listener in rejected: + listener.close() async def open_tunnel( profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None, local_port: int = 0, + *, excluded_ports: set[int] | None = None, ) -> 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) + args = transport_arguments(profile, remote_port, known_hosts) + listener = _listen(local_port, excluded_ports or set()) + tunnel = Tunnel(args, int(listener.getsockname()[1])) 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") + tunnel.server = await asyncio.start_server(tunnel.accept, sock=listener) + return tunnel except BaseException: + listener.close() await tunnel.close() raise diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 620e3b5db..12e4acbce 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -165,6 +165,13 @@ class _WebUIThreadDiagnostics: _WEBUI_MUTATION_PATHS = { "remote.discover": "/api/remote-instances/discover", + "remote.pair_start": "/api/remote-instances/pair_start", + "remote.pair_preview": "/api/remote-instances/pair_preview", + "remote.pair_finish": "/api/remote-instances/pair_finish", + "remote.pair_cancel": "/api/remote-instances/pair_cancel", + "remote.pair_route": "/api/remote-instances/pair_route", + "remote.inspect": "/api/remote-instances/inspect", + "remote.pick_file": "/api/remote-instances/pick_file", "remote.save": "/api/remote-instances/save", "remote.connect": "/api/remote-instances/connect", "remote.disconnect": "/api/remote-instances/disconnect", diff --git a/pyproject.toml b/pyproject.toml index 2734c2452..b510ad68f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,8 @@ dependencies = [ # Feishu's lark-oapi currently requires websockets<16; core supports 15 and 16. "websockets>=15.0,<17.0", "httpx[socks]>=0.28.0,<1.0.0", + "aiohttp>=3.14.3,<4.0.0", + "cryptography>=46.0.0", "ddgs>=9.5.5,<10.0.0", "oauth-cli-kit>=0.1.6,<1.0.0", "loguru>=0.7.3,<1.0.0", diff --git a/tests/cli/test_remote_pair_defaults.py b/tests/cli/test_remote_pair_defaults.py new file mode 100644 index 000000000..458f2d7f8 --- /dev/null +++ b/tests/cli/test_remote_pair_defaults.py @@ -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 diff --git a/tests/utils/test_native_folder_picker.py b/tests/utils/test_native_folder_picker.py index feb5a26de..6b5d8e19a 100644 --- a/tests/utils/test_native_folder_picker.py +++ b/tests/utils/test_native_folder_picker.py @@ -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() diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.py index 93331a30b..008e96c92 100644 --- a/tests/webui/test_gateway_webui_smoke.py +++ b/tests/webui/test_gateway_webui_smoke.py @@ -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)) diff --git a/tests/webui/test_remote_discovery.py b/tests/webui/test_remote_discovery.py new file mode 100644 index 000000000..253008aa3 --- /dev/null +++ b/tests/webui/test_remote_discovery.py @@ -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 diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py index 3a26e4f19..4e80314ae 100644 --- a/tests/webui/test_remote_instances.py +++ b/tests/webui/test_remote_instances.py @@ -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, ) diff --git a/tests/webui/test_remote_pairing.py b/tests/webui/test_remote_pairing.py new file mode 100644 index 000000000..3f999afe7 --- /dev/null +++ b/tests/webui/test_remote_pairing.py @@ -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() diff --git a/tests/webui/test_remote_proxy.py b/tests/webui/test_remote_proxy.py new file mode 100644 index 000000000..38ee56401 --- /dev/null +++ b/tests/webui/test_remote_proxy.py @@ -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 diff --git a/tests/webui/test_remote_tunnel.py b/tests/webui/test_remote_tunnel.py new file mode 100644 index 000000000..85d97c69c --- /dev/null +++ b/tests/webui/test_remote_tunnel.py @@ -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() diff --git a/tests/webui/test_ssh_config.py b/tests/webui/test_ssh_config.py index 785d36e9b..ae2c9ff73 100644 --- a/tests/webui/test_ssh_config.py +++ b/tests/webui/test_ssh_config.py @@ -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): diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 3b7ffd18f..d356d8d77 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -1154,6 +1154,10 @@ function Shell({ const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth); const [sidebarDragging, setSidebarDragging] = useState(false); const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false); + useEffect(() => { + // The drawer portals outside the local host panel; don't leave it over a remote view. + if (!localActive) setMobileSidebarOpen(false); + }, [localActive]); const mobileSidebarRef = useRef(null); const [sessionSearchOpen, setSessionSearchOpen] = useState(false); const mobileWorkbench = useMediaQuery("(max-width: 767px)"); @@ -1287,6 +1291,7 @@ function Shell({ useEffect(() => { const applyRoute = () => { const route = readShellRoute(); + if (route.view === "remote") setMobileSidebarOpen(false); if (currentShellRouteRef.current.view === "settings" && route.view !== "settings" && settingsExitGuardRef.current) { writeShellRoute(currentShellRouteRef.current, true); settingsExitGuardRef.current(() => { @@ -2131,12 +2136,6 @@ function Shell({ setMobileSidebarOpen(false); }, [activeKey, navigate]); - const onOpenRemoteConnections = useCallback(() => { - setSessionSearchOpen(false); - navigate({ view: "remote", activeKey, settingsSection: "overview" }); - setMobileSidebarOpen(false); - }, [activeKey, navigate]); - const onOpenSkills = useCallback(() => { setSessionSearchOpen(false); navigate({ view: "skills", activeKey, settingsSection: "skills" }); @@ -2733,11 +2732,10 @@ function Shell({ onOpenApps, onOpenAutomations, onOpenChannels, - onOpenRemoteConnections, onOpenSkills, onSettingsIntent, onOpenSearch: onOpenSessionSearch, - activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" || view === "remote" ? view : null, + activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" ? view : null, onToggleArchived, pinnedKeys: sidebarPinnedTabKeys, archivedKeys: sidebarArchivedTabKeys, diff --git a/webui/src/components/Sidebar.tsx b/webui/src/components/Sidebar.tsx index 3f4752811..de8cbb452 100644 --- a/webui/src/components/Sidebar.tsx +++ b/webui/src/components/Sidebar.tsx @@ -9,7 +9,6 @@ import { Brain, CalendarClock, MessageCircle, - MonitorUp, PanelLeftClose, Search, Settings, @@ -24,7 +23,6 @@ import { type SidebarPaneGroup, } from "@/components/ChatList"; import { HostSwitcher } from "@/components/remote/HostSwitcher"; -import { useRemoteConnections } from "@/components/remote/RemoteInstances"; import { SIDEBAR_SELECTION_ACTION_ITEM_CLASS, SidebarSelectionHighlight, @@ -70,10 +68,9 @@ interface SidebarProps { onOpenSkills: () => void; onOpenAutomations: () => void; onOpenChannels: () => void; - onOpenRemoteConnections?: () => void; onSettingsIntent?: () => void; onOpenSearch: () => void; - activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null; + activeUtility?: "apps" | "skills" | "automations" | "channels" | null; onToggleArchived: () => void; onCollapse?: () => void; onExpand?: () => void; @@ -111,7 +108,6 @@ function isApplePlatform(): boolean { export function Sidebar(props: SidebarProps) { const { t } = useTranslation(); - const remoteConnections = useRemoteConnections(); const [menuPortalContainer, setMenuPortalContainer] = useState(null); const collapsed = Boolean(props.collapsed); @@ -257,16 +253,6 @@ export function Sidebar(props: SidebarProps) { selectionRef={activeActionRef} icon={} /> - {remoteConnections?.available && props.onOpenRemoteConnections && ( - } - /> - )} {props.archivedCount ? ( (null); function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) { - const { t } = useTranslation(); return { if (event.isComposing) event.preventDefault(); }} onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}> - {t("remote.switchHost")} - picker.select(null)} className="gap-2.5"> + + ; +} + +/** Mounted with the menu so every opening starts with a fresh, stable list. */ +function HostMenuItems({ picker }: { picker: HostPicker }) { + const { t } = useTranslation(); + const [searchable] = useState(() => picker.profiles.length > 5); + const [query, setQuery] = useState(""); + const [order] = useState(() => [picker.currentId, ...picker.recentIds]); + const search = useRef(null); + const list = useRef(null); + const needle = query.trim().toLocaleLowerCase(); + const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle)); + const showLocal = matches(t("remote.local"), picker.localName); + const profiles = picker.profiles.filter(({ name, host }) => matches(name, host)); + if (searchable) { + const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; }; + profiles.sort((a, b) => rank(a.id) - rank(b.id)); + } + useEffect(() => { + // Don't summon the software keyboard when opening the picker on a touch device. + if (!searchable || window.matchMedia("(pointer: coarse)").matches) return; + const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true })); + return () => cancelAnimationFrame(frame); + }, [searchable]); + + return
{ if (document.activeElement === search.current) event.preventDefault(); }} + onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }} + onKeyDownCapture={(event) => { + if (!searchable) return; + if (event.nativeEvent.isComposing) { event.stopPropagation(); return; } + const items = Array.from(event.currentTarget.querySelectorAll('[role="menuitem"]')); + if (event.target === search.current) { + // Keep spaces and IME input out of Radix's menu typeahead. + if (event.key !== "Escape") event.stopPropagation(); + if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") { + event.preventDefault(); + (event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus(); + } else if (event.key === "Enter") { + event.preventDefault(); + if (needle) list.current?.querySelector('[role="menuitem"]')?.click(); + } + } else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) { + event.preventDefault(); event.stopPropagation(); search.current?.focus(); + } + }}> + {searchable ?
+ + setQuery(event.target.value)} autoComplete="off" spellCheck={false} + className="h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" /> +
: {t("remote.switchHost")}} +
+ {showLocal && picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}> {t("remote.local")}{picker.localName} {!picker.currentId && } - - {!!picker.profiles.length && } - {picker.profiles.map((profile) => picker.select(profile.id)} className="gap-2.5"> + } + {showLocal && !!profiles.length && } + {profiles.map((profile) => picker.select(profile.id)} className="gap-2.5" + title={`${profile.name} · ${profile.host}`} aria-current={picker.currentId === profile.id || undefined}> {profile.name}{profile.host} - {picker.pending?.id === profile.id ? : picker.currentId === profile.id ? - : profile.ready ? {t("remote.ready")} : null} + {picker.pending?.id === profile.id ? : picker.currentId === profile.id ? + : profile.ready ? {t("remote.ready")} : null} )} + {!showLocal && !profiles.length &&

{t("remote.noMatchingHosts")}

} +
+
{picker.pending && <>{t("remote.cancelSwitch")}} - {picker.error &&
- {picker.error} + {picker.error &&
+
} {t("remote.manageConnections")} - ; +
+
; } /** Shared sidebar control. Remote frames can only open the trusted shell's menu. */ @@ -70,11 +131,15 @@ export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed const shell = picker.kind === "shell" ? picker : null; const remote = picker.kind === "embedded" || !!shell?.currentId; const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName; - const failed = !!picker.error || !!shell?.offline || status === "error" || status === "closed"; + // A failed switch describes the destination, not the still-active connection. + const failed = !!shell?.offline || status === "error" || status === "closed"; const waiting = !!pendingName || status === "connecting" || status === "reconnecting"; - const label = pendingName ? t("remote.connecting") : picker.name; - const detail = pendingName ? t("remote.preparing", { name: pendingName }) : `${picker.name} · ${picker.hostname}`; - const title = picker.error || `${detail} — ${t(failed ? "remote.offline" : `connection.${status}`)}`; + // The old host stays interactive until the new one is ready. Keep its identity + // visible; progress belongs to the target's row and the accessible status. + const label = picker.name; + const current = `${picker.name} · ${picker.hostname} · ${t(failed ? "remote.offline" : `connection.${status}`)}`; + const detail = pendingName ? `${current} · ${t("remote.preparing", { name: pendingName })}` : current; + const title = picker.error ? `${detail} — ${picker.error}` : detail; const button = ; if (!shell) return button; - return {button}; + // The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation. + return {button}; } /** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */ diff --git a/webui/src/components/remote/PairRouteSettings.tsx b/webui/src/components/remote/PairRouteSettings.tsx new file mode 100644 index 000000000..758a500dc --- /dev/null +++ b/webui/src/components/remote/PairRouteSettings.tsx @@ -0,0 +1,58 @@ +import { useEffect, useRef, useState } from "react"; +import { AlertCircle, Check, Loader2 } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { useClient } from "@/providers/ClientProvider"; +import { remoteAction } from "@/lib/remote-instances"; +import { useRemoteConnections } from "./RemoteInstances"; + +/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */ +export function PairRouteSettings({ id, onSaved }: { id: string; onSaved?: () => void }) { + const { t } = useTranslation(); + const { client } = useClient(); + const connections = useRemoteConnections(); + const hasSavedRoute = !!connections?.directory?.profiles.find((profile) => profile.id === id)?.ssh_config; + const [route, setRoute] = useState(hasSavedRoute ? "saved" : "direct"); + const [original, setOriginal] = useState(route); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [saved, setSaved] = useState(false); + const alive = useRef(true); + useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); + const save = async () => { + setBusy(true); setError(""); setSaved(false); + try { + await remoteAction(client, "pair_route", { id, route_id: route === "direct" ? "" : route }); + if (!alive.current) return; + // Saving and refreshing are different outcomes. Never invite a second save + // merely because the directory refresh failed after the write succeeded. + setOriginal(route); setSaved(true); + try { await connections?.refresh(); } + catch { + if (alive.current) setError(t("remote.errors.directory_unavailable")); + return; + } + if (alive.current) onSaved?.(); + } catch (reason) { + if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") })); + } finally { if (alive.current) setBusy(false); } + }; + return
+

{t("remote.pair.routeHint")}

+ + {error &&

} +
+ {saved &&

{t("remote.saved")}

} + +
+
; +} diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsx new file mode 100644 index 000000000..8ffa004e7 --- /dev/null +++ b/webui/src/components/remote/QuickPairSetup.tsx @@ -0,0 +1,210 @@ +import { useEffect, useId, useRef, useState } from "react"; +import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Disclosure, DisclosureContent } from "@/components/ui/disclosure"; +import { Textarea } from "@/components/ui/textarea"; +import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; +import { useClient } from "@/providers/ClientProvider"; +import { copyTextToClipboard } from "@/lib/clipboard"; +import { remoteAction } from "@/lib/remote-instances"; +import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return"; +import { useRemoteConnections } from "./RemoteInstances"; +import { PairRouteSettings } from "./PairRouteSettings"; + +type Request = { id: string; command: string; expires: number }; +type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string }; + +/** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */ +export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReturn | null; onSSH: () => void; onClose: () => void }) { + const { t } = useTranslation(); + const { client } = useClient(); + const connections = useRemoteConnections(); + const [request, setRequest] = useState(returned ? { id: returned.id, command: "", expires: 0 } : null); + const [preview, setPreview] = useState(null); + const [code, setCode] = useState(returned?.code || ""); + const [saved, setSaved] = useState(""); + const [busy, setBusy] = useState(false); + const [busyVisible, setBusyVisible] = useState(false); + const [error, setError] = useState(""); + const [copied, setCopied] = useState(false); + const [expired, setExpired] = useState(false); + const [manual, setManual] = useState(false); + const [panel, setPanel] = useState<"command" | "help" | null>(null); + const alive = useRef(true); + const initialized = useRef(false); + const requestId = useRef(returned?.id || ""); + const manualInput = useRef(null); + const focusManual = useRef(false); + const codeId = useId(); + const panelId = useId(); + + useEffect(() => { + if (!busy) { setBusyVisible(false); return; } + // Fast local preparation should not flash a loading label or move the dialog. + const timer = window.setTimeout(() => setBusyVisible(true), 200); + return () => window.clearTimeout(timer); + }, [busy]); + + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + // A link opens in a new tab. Closing/reloading the originating page must + // not destroy its key before the new page can validate the receipt. + // Pending invitations are bounded and expire in PairStore. + }; + }, [client]); + useEffect(() => { + if (!request?.expires || saved) return; + const timer = window.setTimeout(() => setExpired(true), Math.max(0, request.expires * 1000 - Date.now())); + return () => window.clearTimeout(timer); + }, [request, saved]); + + const run = async (action: () => Promise) => { + setBusy(true); setError(""); + try { await action(); } + catch (reason) { + if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") })); + } finally { if (alive.current) setBusy(false); } + }; + const start = () => run(async () => { + if (requestId.current) await remoteAction(client, "pair_cancel", { id: requestId.current }); + const result = await remoteAction(client, "pair_start", { return_origin: pairingReturnOrigin() }); + if (!alive.current) { await remoteAction(client, "pair_cancel", { id: result.id }); return; } + requestId.current = result.id; + setRequest(result); setPreview(null); setCode(""); setCopied(false); setExpired(false); setManual(false); setPanel(null); + }); + const review = () => run(async () => { + if (!request) return; + const result = await remoteAction(client, "pair_preview", { id: request.id, code }); + if (alive.current) setPreview(result); + }); + const connect = () => run(async () => { + if (!request || !preview || !connections) return; + let id = saved; + if (!id) { + const result = await remoteAction<{ id: string }>(client, "pair_finish", { id: request.id, code }); + id = result.id; + if (!alive.current) return; + setSaved(id); + } + await connections.refresh(); + if (!alive.current) return; + await connections.connect(id, () => alive.current); + if (alive.current) onClose(); + }); + + useEffect(() => { + if (initialized.current) return; + initialized.current = true; + if (returned) void review(); + else void start(); + // One invitation per mounted dialog, never one per re-render. The returned + // receipt is reviewed only; saving/connecting still requires a user click. + }, []); + const copyCommand = () => { + if (!request) return; + void copyTextToClipboard(request.command).then((ok) => { + if (!alive.current || requestId.current !== request.id || Date.now() >= request.expires * 1000) return; + if (ok) { setCopied(true); setError(""); setPanel(null); } + else { setPanel("command"); setError(t("remote.pair.copyFailed")); } + }); + }; + const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview)); + const reviewingReturn = !!returned && !request?.command && !preview && !manual && !restartAvailable; + const title = preview ? "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add" + : manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add"; + const description = preview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint" + : manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint"; + const showCopied = copied && !manual && !preview && !restartAvailable; + const showBusy = busy && busyVisible; + const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect" + : manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy"; + const busyLabel = preview ? "remote.connecting" : !restartAvailable && (manual || returned) + ? "remote.pair.checkingLink" : "remote.pair.preparing"; + + return <> + +
+ + {showCopied && +
+ {t(description)} + {/* Reserve the longer instruction in either state, including translated text. + It is only a layout spacer, never a second screen-reader announcement. */} + {!preview && !manual && !reviewingReturn && } +
+
+
+
+ {preview ?
+
+

{preview.hostname}

+

{preview.host}

+
+

{t("remote.pair.access")}

+

{t("remote.pair.expiry", { date: new Date(preview.authorized_until * 1000).toLocaleDateString() })}

+ {t("remote.pair.security")}}> +

{t("remote.pair.fingerprint")}

{preview.fingerprint} +

{t("remote.pair.revoke")}

{preview.revoke_command} +
+ {saved && error &&

{t("remote.pair.retryHint")}

+ {t("remote.pair.route")}}> +
} +
: restartAvailable ? null : <> + {manual &&
+