diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md index de45f119f..fe98735ab 100644 --- a/docs/guides/remote-instances.md +++ b/docs/guides/remote-instances.md @@ -25,6 +25,8 @@ The return link targets only an HTTP loopback origin (`127.0.0.1`, `localhost`, 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. +Quick pairing can coexist with an existing HTTPS reverse proxy and a configured `publicWsUrl`. Keep that URL for browsers that connect directly. SSH uses the Gateway's plain HTTP listener on loopback, not the public URL. Quick pairing does not support TLS on the Gateway listener itself or `trustedProxyAuth`; it still requires a configured WebUI secret and explicit authorization. + 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. @@ -66,7 +68,7 @@ You can also paste a simple command, for example `ssh -p 2222 -i "~/.ssh/team ke - Run the local WebUI on a loopback address, using the system OpenSSH client. - 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 a configured `tokenIssueSecret` (or `token`) in its configuration file. -- The remote gateway must support the authenticated `/webui/terminal` identity probe and the supported WebUI client contract. The local installation must have its WebUI bundle; the remote host only needs the backend endpoints. The initial transport supports HTTP on the server's loopback address; SSH encrypts the connection. A configured public WebSocket URL or trusted-proxy authentication is not supported by this SSH connection mode. +- The remote gateway must support the authenticated `/webui/terminal` identity probe and the supported WebUI client contract. The local installation must have its WebUI bundle; the remote host only needs the backend endpoints. The transport uses HTTP on the server's loopback address; SSH encrypts the connection. The **Use existing SSH settings** flow does not support a configured public WebSocket URL or trusted-proxy authentication. 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 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. @@ -139,4 +141,4 @@ SSH authenticates the server. A read-only, fixed Python probe retrieves only Web Remote-connection actions require an authenticated local WebUI connection, a loopback-bound gateway, and local request origin. They are unavailable from a public/reverse-proxied administration page. Connecting requires server admin 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. +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 and interactive SSH passwords need additional setup; this flow does not silently weaken their authentication. diff --git a/nanobot/webui/remote_pair_server.py b/nanobot/webui/remote_pair_server.py index 888a9a52e..e5e604f8a 100644 --- a/nanobot/webui/remote_pair_server.py +++ b/nanobot/webui/remote_pair_server.py @@ -17,7 +17,7 @@ import subprocess import sys import tempfile from pathlib import Path -from typing import Any +from typing import Any, TypedDict from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write, public_key, seal from nanobot.webui.remote_ssh import RemoteError @@ -70,22 +70,38 @@ def bridge_source(port: int, until: int) -> str: return _BRIDGE.replace("PORT", str(port)).replace("UNTIL", str(until)) -def metadata(config: Path) -> dict[str, Any]: - """Read only the WebUI credential out of the operator-selected config.""" +class PairingTarget(TypedDict): + port: int + secret: str + hostname: str + config_path: str + token_issue_path: str + + +def metadata(config: Path) -> PairingTarget: + """Read the fixed loopback target and its credential from the 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"): + # publicWsUrl advertises the browser route. The SSH bridge does not + # use that URL, but does require a plain HTTP listener on loopback. + certfile = ws.get("sslCertfile") or ws.get("ssl_certfile") or "" + if (isinstance(certfile, str) and certfile.strip()) 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: + issue_path = ws.get("tokenIssuePath") or ws.get("token_issue_path") or "" + if type(port) is not int or not 1 <= port <= 65535 or not isinstance(issue_path, str): 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 ""} + return { + "port": port, + "secret": secret, + "hostname": socket.gethostname(), + "config_path": str(config.resolve()), + "token_issue_path": issue_path, + } except PermissionError: raise RemoteError("config_permission") from None except (OSError, ValueError, TypeError, AttributeError): diff --git a/tests/webui/test_remote_pairing.py b/tests/webui/test_remote_pairing.py index ded8bcf8c..8a9dae567 100644 --- a/tests/webui/test_remote_pairing.py +++ b/tests/webui/test_remote_pairing.py @@ -7,7 +7,7 @@ import sys import threading import time from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest from cryptography.hazmat.primitives import serialization @@ -456,11 +456,53 @@ async def test_paired_profile_follows_moved_data_root(tmp_path, monkeypatch, wit assert len(RemoteInstances(moved).snapshot()["profiles"]) == 1 -def test_model_keys_never_enter_pairing_metadata(tmp_path): +@pytest.mark.parametrize("field", ["publicWsUrl", "public_ws_url"]) +def test_authorize_with_public_websocket_keeps_only_the_private_gateway_target(pair, tmp_path, monkeypatch, field): + store, _, request, original, _ = pair 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)) + before = json.dumps({ + "providers": {"deepseek": {"apiKey": "not-exported"}}, + "channels": {"websocket": {"enabled": True, "port": 8865, "tokenIssueSecret": "webui-only", + field: "wss://example.test/chat", "path": "/chat"}}, + }) + path.write_text(before) + install = Mock() + monkeypatch.setattr(remote_pair_server, "as_account", install) + + code = remote_pair_server.authorize(request, host=original.host, user=original.user, ssh_port=22, + config=path, host_key=original.host_key, until=original.authorized_until) + + saved = store.finish(request.id, code) + assert saved.port == 8865 and saved.secret == "webui-only" + assert saved.config_path == str(path.resolve()) + assert "wss://" not in saved.model_dump_json() and "not-exported" not in saved.model_dump_json() + install.assert_called_once_with( + original.user, "install", {"request": request.model_dump(), "port": 8865, "until": original.authorized_until}, + ) + assert path.read_text() == before + + +@pytest.mark.parametrize(("settings", "error"), [ + ({"trustedProxyAuth": {"assertionHeader": "X-User", "trustedPeerCidrs": ["127.0.0.1/32"]}}, + "incompatible_gateway"), + ({"trusted_proxy_auth": {"assertion_header": "X-User", "trusted_peer_cidrs": ["127.0.0.1/32"]}}, + "incompatible_gateway"), + ({"sslCertfile": "/etc/nanobot/cert.pem", "sslKeyfile": "/etc/nanobot/key.pem"}, "incompatible_gateway"), + ({"tokenIssueSecret": ""}, "webui_auth_required"), +]) +def test_public_websocket_does_not_override_ssh_pairing_requirements(pair, tmp_path, monkeypatch, settings, error): + _, _, request, original, _ = pair + path = tmp_path / "config.json" + path.write_text(json.dumps({"channels": {"websocket": { + "enabled": True, "tokenIssueSecret": "webui-only", "publicWsUrl": "wss://example.test/chat", + "path": "/chat", **settings, + }}})) + install = Mock() + monkeypatch.setattr(remote_pair_server, "as_account", install) + with pytest.raises(RemoteError, match=f"^{error}$"): + remote_pair_server.authorize(request, host=original.host, user=original.user, ssh_port=22, + config=path, host_key=original.host_key, until=original.authorized_until) + install.assert_not_called() def test_pairing_modules_can_import_without_posix_server_dependencies(): diff --git a/tests/webui/test_remote_proxy.py b/tests/webui/test_remote_proxy.py index 3ddbbbec7..c4abe727d 100644 --- a/tests/webui/test_remote_proxy.py +++ b/tests/webui/test_remote_proxy.py @@ -242,6 +242,23 @@ async def test_remote_credentials_never_leave_the_backend(remote): assert request.headers["Authorization"] != "Bearer " + issued["api_token"] +async def test_public_websocket_url_does_not_redirect_the_ssh_proxy(remote): + public_url = "wss://public.test/custom/ws" + remote.services.http.config.public_ws_url = public_url + host = f"http://127.0.0.1:{remote.port}" + direct = await remote.client.get(host + "/webui/bootstrap", headers={"X-Nanobot-Auth": ROOT}) + assert direct.status_code == 200 and direct.json()["ws_url"] == public_url + + for attempt in range(2): + issued = await bootstrap(remote) + assert issued["ws_url"].startswith(f"ws://127.0.0.1:{remote.proxy.port}/remote-session/") + assert public_url not in json.dumps(issued) + async with connect(issued["ws_url"] + "?token=" + issued["token"], origin=remote.proxy.origin) as ws: + assert json.loads(await ws.recv())["ready"] is True + await ws.send(f'{{"synthetic_turn":{attempt}}}') + assert json.loads(await ws.recv())["synthetic_turn"] == attempt + + @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)