Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(remote): discover cloud login accounts before asking users
Xubin Renf4e45c98d7d2
diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.mdindex 28547ba0b..84609ec88 100644--- a/docs/guides/remote-instances.md+++ b/docs/guides/remote-instances.md@@ -4,7 +4,7 @@ Open your local **nanobot WebUI**, click the current host (initially **Local**)at the bottom of the sidebar, and choose **Manage connections…**. This is thesingle entry point for switching and managing hosts. The page lists this computerand your saved servers. Choose-**Add server** to copy a prepared pairing command, or choose **Other ways → Use existing SSH settings**+**Connect to remote nanobot** 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@@ -16,7 +16,7 @@ computer stays at the top. Only the host list scrolls, so **Manage connectionsstays visible. Use the arrow keys to choose a result, Enter to connect, and Escapeto 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+To add another server, choose **Connect to remote nanobot** below your saved connections. Use aserver's menu to edit or forget it. Editing opens the same dialog; **Save changes**saves without connecting or switching hosts. Disconnect an open server beforeediting its connection settings. The page supports browser back/forward and the@@ -34,7 +34,7 @@ It is separate from remote execution/worker deployment.For a Linux server with this version of nanobot installed, you do not need toprepare a local SSH key or know the service account/config path:-1. In your **local** WebUI choose **Add server → Copy command**. The command is+1. In your **local** WebUI choose **Connect to remote nanobot → Copy command**. The command isprepared 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.@@ -42,10 +42,17 @@ prepare a local SSH key or know the service account/config path:2. Open your cloud provider's server terminal. Run the command in the environmentwhere 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+ choose a configuration if there is more than one. The connection account is+ detected from your current login, the original login under sudo, or the only+ regular account. In a root cloud console with several accounts, pairing checks+ [cloud-init's configured default user](https://docs.cloud-init.io/en/latest/explanation/instancedata.html)+ and uses it only if it matches an existing regular login account. It queries+ only the username, not passwords or other instance data. No account name or+ password needs to be entered when detection succeeds. If the account is still+ ambiguous, choose from a numbered list; this is an account **on this server**,+ not your cloud website account. Invalid numbers can be corrected without+ restarting pairing. No account is created and no device is authorized by making+ that choice. The account is shown in the authorization summary. A globalserver address reported by the SSH session can also be selected automatically.On recognized Tencent Cloud Linux instances, pairing can instead read thisserver's public IPv4 from the fixed, instance-local metadata endpoint, withoutdiff --git a/nanobot/cli/remote.py b/nanobot/cli/remote.pyindex 5281cc26e..eb765d913 100644--- a/nanobot/cli/remote.py+++ b/nanobot/cli/remote.py@@ -14,7 +14,6 @@ from pathlib import Pathfrom typing import NoReturnimport typer-from click import IntRangeapp = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")@@ -66,18 +65,74 @@ def _tencent_public_host() -> str:connection.close()+def _ssh_login_users() -> list[str]:+ """List regular interactive accounts, not root or service identities."""+ import pwd++ return sorted(u.pw_name for u in pwd.getpwall()+ if 1000 <= u.pw_uid < 65534 and u.pw_shell.endswith(("/bash", "/sh", "/zsh")))+++def _cloud_ssh_user() -> str | None:+ """Read only cloud-init's configured login name, never its full instance data."""+ cloud_init = shutil.which("cloud-init")+ if not cloud_init:+ return None+ try:+ result = subprocess.run([cloud_init, "query", "system_info.default_user.name"],+ capture_output=True, text=True, timeout=2, check=False)+ except (OSError, UnicodeError, subprocess.SubprocessError):+ return None+ return result.stdout.strip() if result.returncode == 0 else None++def _default_ssh_user() -> str | None:- """Suggest the existing login account, including when invoked through sudo."""+ """Prefer the current login, then the cloud image's existing default account."""import pwdcurrent = 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"))]+ users = _ssh_login_users()sudo_user = os.environ.get("SUDO_USER")if sudo_user in users:return sudo_user- return users[0] if len(users) == 1 else None+ if len(users) == 1:+ return users[0]+ if users:+ cloud_user = _cloud_ssh_user()+ if cloud_user in users:+ return cloud_user+ return None+++def _choose_number(prompt: str, count: int) -> int:+ """Keep invalid selections in the current step, including across Typer versions."""+ while True:+ choice = int(typer.prompt(prompt, type=int))+ if 1 <= choice <= count:+ return choice+ typer.echo(f"Please choose a number from 1 to {count}.")+++def _choose_ssh_user() -> str:+ """Ask only when discovery is ambiguous; never make the user invent a name."""+ user = _default_ssh_user()+ if user:+ return user+ users = _ssh_login_users()+ if not users:+ typer.echo("No regular login account was found on this server.\n"+ "Ask the server administrator to set up a non-root login account, then try again.\n"+ "No device was authorized and no server accounts were changed.")+ raise typer.Exit(1)+ typer.echo("\nThis server has several login accounts.\n"+ "Choose the one you normally use to log into this server, not your cloud website account.\n"+ "No password is needed here. If unsure, press Ctrl+C and ask the server administrator.")+ for index, name in enumerate(users, 1):+ typer.echo(f" {index}. {name}")+ choice = _choose_number("Choose an account number", len(users))+ return users[choice - 1]def _pair_as_administrator(request: str, config: Path, host: str, ssh_user: str, port: int) -> NoReturn:@@ -143,7 +198,7 @@ def pair(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))))+ choice = _choose_number("Which nanobot?", len(candidates))config = Path(candidates[choice - 1].config_path)else:config = Path(typer.prompt("Path to your nanobot config"))@@ -156,7 +211,7 @@ def pair(raise_pair_as_administrator(request, config, host, ssh_user, port)if not ssh_user:- ssh_user = _default_ssh_user() or typer.prompt("SSH login account")+ ssh_user = _choose_ssh_user()if not host:host = _default_host()if not host:diff --git a/tests/cli/test_remote_pair_admin.py b/tests/cli/test_remote_pair_admin.pyindex c20f2a930..8b2d3ea7a 100644--- a/tests/cli/test_remote_pair_admin.py+++ b/tests/cli/test_remote_pair_admin.py@@ -10,6 +10,7 @@ import pytestfrom typer.testing import CliRunnerfrom nanobot.cli import remote+from nanobot.cli.remote import _default_ssh_userfrom nanobot.webui import remote_pair_serverfrom nanobot.webui.remote_pairing import PairStore, read_requestfrom nanobot.webui.remote_ssh import RemoteError@@ -199,3 +200,93 @@ def test_explicit_host_skips_address_detection(protected, monkeypatch):assert result.exit_code == 0, result.outputassert "on this server ([email protected])" in result.outputdetect.assert_not_called()+++def test_root_console_with_two_accounts_goes_straight_to_device_consent(protected, monkeypatch):+ pwd = pytest.importorskip("pwd")+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ monkeypatch.setattr(remote.os, "getuid", lambda: 0)+ monkeypatch.setattr(pwd, "getpwuid", lambda _: SimpleNamespace(pw_uid=0, pw_name="root"))+ monkeypatch.delenv("SUDO_USER", raising=False)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: ["lighthouse", "ubuntu"])+ monkeypatch.setattr(remote, "_cloud_ssh_user", lambda: "ubuntu")+ monkeypatch.setattr(remote, "_default_ssh_user", _default_ssh_user)+ result = CliRunner().invoke(remote.app, protected.args, input="n\n")+ assert result.exit_code == 0, result.output+ assert "on this server ([email protected])" in result.output+ assert "Authorize this computer?" in result.output+ assert "SSH login account" not in result.output+ assert "Choose an account" not in result.output+ protected.authorize.assert_not_called()+++def test_ambiguous_accounts_are_numbered_and_explained_before_consent(protected, monkeypatch):+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ monkeypatch.setattr(remote, "_default_ssh_user", lambda: None)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: ["deploy", "ubuntu"])+ result = CliRunner().invoke(remote.app, protected.args, input="not-a-number\n0\n3\n2\nn\n")+ assert result.exit_code == 0, result.output+ assert "1. deploy" in result.output and "2. ubuntu" in result.output+ assert "not your cloud website account" in result.output+ assert "No password is needed here" in result.output+ assert "on this server ([email protected])" in result.output+ assert "SSH login account:" not in result.output+ assert result.output.count("Choose an account number") == 4+ assert result.output.count("Please choose a number from 1 to 2") == 2+ protected.authorize.assert_not_called()+++def test_account_picker_can_be_cancelled_without_authorizing(protected, monkeypatch):+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ monkeypatch.setattr(remote, "_default_ssh_user", lambda: None)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: ["deploy", "ubuntu"])+ result = CliRunner().invoke(remote.app, protected.args, input="")+ assert result.exit_code == 1, result.output+ assert "Authorize this computer?" not in result.output+ protected.authorize.assert_not_called()+++def test_no_login_accounts_explains_recovery_without_asking_for_a_name(protected, monkeypatch):+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ monkeypatch.setattr(remote, "_default_ssh_user", lambda: None)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: [])+ result = CliRunner().invoke(remote.app, protected.args)+ assert result.exit_code == 1, result.output+ assert "No regular login account was found on this server" in result.output+ assert "No device was authorized" in result.output+ assert "Choose an account number" not in result.output+ assert "Authorize this computer?" not in result.output+ protected.authorize.assert_not_called()+++def test_explicit_account_skips_discovery_and_selection(protected, monkeypatch):+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ choose = Mock(side_effect=AssertionError("explicit account must win"))+ monkeypatch.setattr(remote, "_choose_ssh_user", choose)+ result = CliRunner().invoke(remote.app, protected.args + ["--ssh-user", "deploy"], input="n\n")+ assert result.exit_code == 0, result.output+ assert "on this server ([email protected])" in result.output+ choose.assert_not_called()+ protected.authorize.assert_not_called()+++def test_multiple_nanobots_keep_invalid_choices_in_the_selection_step(protected):+ protected.metadata.side_effect = None+ protected.metadata.return_value = {"port": 8765}+ protected.run.return_value = SimpleNamespace(stdout="NANOBOT_REMOTE:" + json.dumps({+ "hostname": "team", "incomplete": False, "candidates": [+ {"config_path": str(protected.config), "runtime_user": "nanobot", "service": "nanobot-team.service"},+ {"config_path": str(protected.config.parent / "other.json"), "runtime_user": "nanobot", "service": "other.service"},+ ],+ }))+ result = CliRunner().invoke(remote.app, ["pair", protected.request], input="0\n3\n1\nn\n")+ assert result.exit_code == 0, result.output+ assert result.output.count("Which nanobot?") == 3+ assert result.output.count("Please choose a number from 1 to 2") == 2+ protected.metadata.assert_called_once_with(protected.config)+ protected.authorize.assert_not_called()diff --git a/tests/cli/test_remote_pair_defaults.py b/tests/cli/test_remote_pair_defaults.pyindex 016a21e21..ef843c212 100644--- a/tests/cli/test_remote_pair_defaults.py+++ b/tests/cli/test_remote_pair_defaults.py@@ -1,6 +1,8 @@"""Server pairing suggests a real login account, never blindly trusts SUDO_USER."""+import subprocessfrom types import SimpleNamespace+from unittest.mock import Mockimport pytest@@ -14,6 +16,7 @@ from nanobot.cli import remote)def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expected):pwd = pytest.importorskip("pwd")+ monkeypatch.setattr(remote, "_cloud_ssh_user", lambda: None)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")]]@@ -24,6 +27,67 @@ def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expecassert remote._default_ssh_user() == expected[email protected]("configured, expected", [+ ("ubuntu", "ubuntu"), ("lighthouse", "lighthouse"), ("root", None),+ ("nanobot", None), ("missing", None), ("ubuntu\nlighthouse", None), (None, None),+])+def test_root_cloud_console_uses_only_an_existing_regular_cloud_account(monkeypatch, configured, expected):+ pwd = pytest.importorskip("pwd")+ monkeypatch.setattr(remote.os, "getuid", lambda: 0)+ monkeypatch.setattr(pwd, "getpwuid", lambda _: SimpleNamespace(pw_uid=0, pw_name="root"))+ monkeypatch.delenv("SUDO_USER", raising=False)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: ["lighthouse", "ubuntu"])+ monkeypatch.setattr(remote, "_cloud_ssh_user", lambda: configured)+ assert remote._default_ssh_user() == expected++[email protected]("uid,sudo_user,users,expected", [+ (1001, "", ["deploy", "ubuntu"], "deploy"),+ (0, "deploy", ["deploy", "ubuntu"], "deploy"),+ (0, "", ["deploy"], "deploy"), (0, "", [], None),+])+def test_known_login_and_single_account_do_not_need_cloud_lookup(monkeypatch, uid, sudo_user, users, expected):+ pwd = pytest.importorskip("pwd")+ monkeypatch.setattr(remote.os, "getuid", lambda: uid)+ monkeypatch.setattr(pwd, "getpwuid", lambda _: SimpleNamespace(pw_uid=uid, pw_name="deploy" if uid else "root"))+ monkeypatch.setenv("SUDO_USER", sudo_user)+ monkeypatch.setattr(remote, "_ssh_login_users", lambda: users)+ lookup = Mock(side_effect=AssertionError("unnecessary cloud lookup"))+ monkeypatch.setattr(remote, "_cloud_ssh_user", lookup)+ assert remote._default_ssh_user() == expected+ lookup.assert_not_called()+++def test_cloud_lookup_reads_only_the_configured_username_with_a_timeout(monkeypatch):+ monkeypatch.setattr(remote.shutil, "which", lambda _: "/usr/bin/cloud-init")+ run = Mock(return_value=SimpleNamespace(returncode=0, stdout="ubuntu\n"))+ monkeypatch.setattr(remote.subprocess, "run", run)+ assert remote._cloud_ssh_user() == "ubuntu"+ run.assert_called_once_with(["/usr/bin/cloud-init", "query", "system_info.default_user.name"],+ capture_output=True, text=True, timeout=2, check=False)++[email protected]("failure", [OSError(), UnicodeError(), subprocess.TimeoutExpired("cloud-init", 2)])+def test_unavailable_cloud_data_keeps_the_account_picker(monkeypatch, failure):+ monkeypatch.setattr(remote.shutil, "which", lambda _: "/usr/bin/cloud-init")+ monkeypatch.setattr(remote.subprocess, "run", Mock(side_effect=failure))+ assert remote._cloud_ssh_user() is None+++def test_failed_cloud_query_does_not_use_error_output_as_an_account(monkeypatch):+ monkeypatch.setattr(remote.shutil, "which", lambda _: "/usr/bin/cloud-init")+ monkeypatch.setattr(remote.subprocess, "run", Mock(return_value=SimpleNamespace(returncode=1, stdout="ubuntu")))+ assert remote._cloud_ssh_user() is None+++def test_missing_cloud_init_does_not_run_an_external_command(monkeypatch):+ monkeypatch.setattr(remote.shutil, "which", lambda _: None)+ run = Mock()+ monkeypatch.setattr(remote.subprocess, "run", run)+ assert remote._cloud_ssh_user() is None+ run.assert_not_called()++@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", ""),