fix(remote): detect Tencent public address and clarify this-server prompts

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 92b0f1d285
commit e59c2bf79a
5 files changed
+189 -9

No files matched your search

+9 -2
View File
@@ -46,8 +46,15 @@ prepare a local SSH key or know the service account/config path:
IP/hostname and an existing non-root SSH login account when prompted. IP/hostname and an existing non-root SSH login account when prompted.
A single existing login account (including the original account under sudo) A single existing login account (including the original account under sudo)
is selected automatically and shown in the authorization summary. A global is selected automatically and shown in the authorization summary. A global
server address reported by the SSH session can also be selected automatically; 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. On recognized Tencent Cloud Linux instances, pairing can instead read this
server's public IPv4 from the fixed, instance-local metadata endpoint, without
cloud API keys. Only that public-address field is read; no role credentials or
user data are requested. If neither source is available, enter **this server's**
public IP from the cloud console, not your computer's IP. Private addresses and
public-IP lookup services (which may report a shared NAT/proxy) are not used.
The detected address is shown in the authorization summary, not proof that SSH
is reachable. Use `--ssh-user` or `--host` to override.
3. Review the **full nanobot access** authorization on the server and confirm it. 3. Review the **full nanobot access** authorization on the server and confirm it.
If its config belongs to another service account, the command first asks If its config belongs to another service account, the command first asks
**Continue as server administrator?**. Confirm to continue via your existing **Continue as server administrator?**. Confirm to continue via your existing
+45 -7
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import http.client
import ipaddress import ipaddress
import os import os
import shlex import shlex
@@ -19,17 +20,50 @@ app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI o
def _default_host() -> str: def _default_host() -> str:
"""Use only a globally reachable address reported by this SSH session. """Suggest this server's address from the SSH session or instance metadata.
A cloud's outbound address or a NAT/private address is not evidence of the Outbound-IP lookup services can return a shared NAT/proxy, not this server.
inbound SSH destination. Do not contact an external IP lookup service. Only the recognized cloud's fixed public-address metadata field is queried.
""" """
fields = os.environ.get("SSH_CONNECTION", "").split() fields = os.environ.get("SSH_CONNECTION", "").split()
try: try:
address = ipaddress.ip_address(fields[2]) if len(fields) == 4 else None address = ipaddress.ip_address(fields[2]) if len(fields) == 4 else None
return str(address) if address and address.is_global else "" if address and address.is_global and not address.is_multicast:
return str(address)
except ValueError: except ValueError:
pass
return _tencent_public_host()
def _tencent_public_host() -> str:
"""Read one non-secret field on Tencent instances; never probe other clouds.
This is an operator-run setup command, not an agent HTTP tool. Keep metadata
access fixed and local: no arbitrary URLs, redirects, proxies or credentials.
A literal link-local endpoint avoids DNS/proxy delays on non-cloud networks.
Unsupported installations and unavailable metadata keep the manual fallback.
"""
try:
if sys.platform != "linux" or Path("/sys/class/dmi/id/sys_vendor").read_text().strip() != "Tencent Cloud":
return ""
except (OSError, UnicodeError):
return "" return ""
connection = http.client.HTTPConnection("169.254.0.23", timeout=1)
try:
connection.request("GET", "/latest/meta-data/public-ipv4",
headers={"Host": "metadata.tencentyun.com"})
response = connection.getresponse()
if response.status != 200:
return ""
raw = response.read(64)
if len(raw) >= 64:
return ""
address = ipaddress.IPv4Address(raw.decode("ascii").strip())
return str(address) if address.is_global and not address.is_multicast else ""
except (OSError, ValueError, http.client.HTTPException):
return ""
finally:
connection.close()
def _default_ssh_user() -> str | None: def _default_ssh_user() -> str | None:
@@ -79,7 +113,7 @@ def _pair_as_administrator(request: str, config: Path, host: str, ssh_user: str,
@app.command() @app.command()
def pair( def pair(
request: str = typer.Argument(help="Public pairing request copied from your local WebUI"), 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"), host: str = typer.Option("", help="Public IP or hostname of this server, reachable from your computer"),
ssh_user: str = typer.Option("", help="Existing non-root SSH login account"), 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"), 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"), config: Path | None = typer.Option(None, help="Existing nanobot config; discovered if omitted"),
@@ -124,8 +158,12 @@ def pair(
if not ssh_user: if not ssh_user:
ssh_user = _default_ssh_user() or typer.prompt("SSH login account") ssh_user = _default_ssh_user() or typer.prompt("SSH login account")
if not host: if not host:
host = _default_host() or typer.prompt("Server public IP or hostname (shown in your cloud console)") host = _default_host()
typer.echo(f"\nAuthorize {invitation.label} to use nanobot on {ssh_user}@{host}?\nConfig: {config}\nServer fingerprint: {fingerprint(host_key)}") if not host:
typer.echo("Could not detect this server's public address.\n"
"Use the public IP shown for this server in your cloud console, not your computer's IP.")
host = typer.prompt("This server's public IP or hostname")
typer.echo(f"\nAuthorize {invitation.label} to use nanobot on this server ({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.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.")
if not typer.confirm("Authorize this computer?", default=False): if not typer.confirm("Authorize this computer?", default=False):
typer.echo("Cancelled. No device was authorized. Run the pairing command again when ready.") typer.echo("Cancelled. No device was authorized. Run the pairing command again when ready.")
+34
View File
@@ -165,3 +165,37 @@ def test_protected_parent_directory_offers_same_recovery(protected, monkeypatch)
assert "Continue as server administrator?" in result.output assert "Continue as server administrator?" in result.output
protected.metadata.assert_not_called() protected.metadata.assert_not_called()
protected.run.assert_not_called() protected.run.assert_not_called()
def test_detected_address_skips_ip_prompt_and_identifies_this_server(protected):
protected.metadata.side_effect = None
protected.metadata.return_value = {"port": 8765}
result = CliRunner().invoke(remote.app, protected.args, input="n\n")
assert result.exit_code == 0, result.output
assert "on this server (ubuntu@8.8.8.8)" in result.output
assert "This server's public IP or hostname:" not in result.output
assert "Could not detect" not in result.output
protected.authorize.assert_not_called()
def test_manual_fallback_names_this_server_not_the_local_computer(protected, monkeypatch):
protected.metadata.side_effect = None
protected.metadata.return_value = {"port": 8765}
monkeypatch.setattr(remote, "_default_host", lambda: "")
result = CliRunner().invoke(remote.app, protected.args, input="43.156.243.141\nn\n")
assert result.exit_code == 0, result.output
assert "This server's public IP or hostname:" in result.output
assert "not your computer's IP" in result.output
assert "on this server (ubuntu@43.156.243.141)" in result.output
protected.authorize.assert_not_called()
def test_explicit_host_skips_address_detection(protected, monkeypatch):
protected.metadata.side_effect = None
protected.metadata.return_value = {"port": 8765}
detect = Mock()
monkeypatch.setattr(remote, "_default_host", detect)
result = CliRunner().invoke(remote.app, protected.args + ["--host", "server.example"], input="n\n")
assert result.exit_code == 0, result.output
assert "on this server (ubuntu@server.example)" in result.output
detect.assert_not_called()
+1
View File
@@ -32,4 +32,5 @@ def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expec
]) ])
def test_only_global_ssh_server_address_can_be_suggested(monkeypatch, connection, expected): def test_only_global_ssh_server_address_can_be_suggested(monkeypatch, connection, expected):
monkeypatch.setenv("SSH_CONNECTION", connection) monkeypatch.setenv("SSH_CONNECTION", connection)
monkeypatch.setattr(remote, "_tencent_public_host", lambda: "")
assert remote._default_host() == expected assert remote._default_host() == expected
+100
View File
@@ -0,0 +1,100 @@
"""Pairing knows whose public IP it needs, without querying arbitrary metadata."""
import http.client
from pathlib import Path
from unittest.mock import Mock
import pytest
from nanobot.cli import remote
@pytest.fixture
def metadata(monkeypatch):
monkeypatch.setattr(remote.sys, "platform", "linux")
monkeypatch.setattr(Path, "read_text", lambda _: "Tencent Cloud\n")
response = Mock(status=200)
response.read.return_value = b"43.156.243.141\n"
connection = Mock()
connection.getresponse.return_value = response
factory = Mock(return_value=connection)
monkeypatch.setattr(remote.http.client, "HTTPConnection", factory)
return factory, connection, response
def test_tencent_uses_only_fixed_public_address_field(metadata, monkeypatch):
factory, connection, response = metadata
monkeypatch.setenv("HTTP_PROXY", "http://proxy.invalid:8888")
assert remote._tencent_public_host() == "43.156.243.141"
factory.assert_called_once_with("169.254.0.23", timeout=1)
connection.request.assert_called_once_with("GET", "/latest/meta-data/public-ipv4",
headers={"Host": "metadata.tencentyun.com"})
response.read.assert_called_once_with(64)
connection.close.assert_called_once()
@pytest.mark.parametrize("vendor", ["Amazon EC2", "Google", "QEMU", "", "Tencent Cloud impostor"])
def test_other_machines_do_not_probe_metadata(metadata, monkeypatch, vendor):
factory, _, _ = metadata
monkeypatch.setattr(Path, "read_text", lambda _: vendor)
assert remote._tencent_public_host() == ""
factory.assert_not_called()
@pytest.mark.parametrize("platform", ["darwin", "win32"])
def test_non_linux_never_probes(metadata, monkeypatch, platform):
factory, _, _ = metadata
monkeypatch.setattr(remote.sys, "platform", platform)
assert remote._tencent_public_host() == ""
factory.assert_not_called()
@pytest.mark.parametrize("error", [PermissionError(), FileNotFoundError(), UnicodeError()])
def test_unreadable_machine_identity_falls_back(metadata, monkeypatch, error):
factory, _, _ = metadata
monkeypatch.setattr(Path, "read_text", Mock(side_effect=error))
assert remote._tencent_public_host() == ""
factory.assert_not_called()
@pytest.mark.parametrize("value", [b"10.0.0.8", b"127.0.0.1", b"169.254.0.23", b"100.64.0.1",
b"0.0.0.0", b"224.0.0.1", b"255.255.255.255", b"::1", b"2606:4700::1111",
b"8.8.8.8\n1.1.1.1", b"host.example", b"", b"\xff", b"x" * 64,
b"8.8.8.8" + b" " * 57, b"{\"credentials\":\"never-used\"}"])
def test_only_one_bounded_global_ipv4_is_accepted(metadata, value):
_, connection, response = metadata
response.read.return_value = value
assert remote._tencent_public_host() == ""
connection.close.assert_called_once()
@pytest.mark.parametrize("status", [301, 302, 401, 403, 404, 500])
def test_redirects_and_errors_are_not_followed(metadata, status):
_, connection, response = metadata
response.status = status
assert remote._tencent_public_host() == ""
response.read.assert_not_called()
assert connection.request.call_count == 1
connection.close.assert_called_once()
@pytest.mark.parametrize("error", [TimeoutError(), ConnectionRefusedError(), http.client.HTTPException()])
def test_failed_lookup_falls_back_and_closes_connection(metadata, error):
_, connection, _ = metadata
connection.getresponse.side_effect = error
assert remote._tencent_public_host() == ""
connection.close.assert_called_once()
@pytest.mark.parametrize("ssh_connection", ["", "proxy 50000 10.0.0.8 22", "invalid",
"proxy 50000 224.0.0.1 22"])
def test_cloud_console_without_public_ssh_address_uses_instance_metadata(metadata, monkeypatch, ssh_connection):
monkeypatch.setenv("SSH_CONNECTION", ssh_connection)
assert remote._default_host() == "43.156.243.141"
def test_public_ssh_address_takes_precedence(metadata, monkeypatch):
factory, _, _ = metadata
monkeypatch.setenv("SSH_CONNECTION", "1.1.1.1 50000 8.8.8.8 22")
assert remote._default_host() == "8.8.8.8"
factory.assert_not_called()