fix(remote): guide protected-config pairing through explicit admin consent
This commit is contained in:
1 parent
442055d9fc
commit
3ac60f0780
13 files changed
+224
-14
No files matched your search
@@ -49,8 +49,13 @@ prepare a local SSH key or know the service account/config path:
|
||||
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.
|
||||
If its config belongs to another service account, the command first asks
|
||||
**Continue as server administrator?**. Confirm to continue via your existing
|
||||
sudo access (your server login password may be required). The same installation,
|
||||
config and SSH login account are retained; you do not need to rewrite the command.
|
||||
Declining leaves everything unchanged. Without sudo access, ask the server
|
||||
administrator to run the command. Pairing does not install sudo rules or weaken
|
||||
config permissions, and device authorization still requires a separate confirmation.
|
||||
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**.
|
||||
|
||||
+41
-2
@@ -4,10 +4,13 @@ from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import NoReturn
|
||||
|
||||
import typer
|
||||
from click import IntRange
|
||||
@@ -43,6 +46,36 @@ def _default_ssh_user() -> str | None:
|
||||
return users[0] if len(users) == 1 else None
|
||||
|
||||
|
||||
def _pair_as_administrator(request: str, config: Path, host: str, ssh_user: str, port: int) -> NoReturn:
|
||||
"""Continue the same request only with the operator's explicit sudo consent."""
|
||||
typer.echo("\nnanobot's configuration is protected by another server account.")
|
||||
typer.echo(f"Config: {config}\nAdministrator access is needed to continue. File permissions will not change.")
|
||||
# Keep the installed environment (resolving a venv Python symlink loses it).
|
||||
# Isolated mode excludes CWD/PYTHONPATH; never forward the caller's environment
|
||||
# with sudo -E or re-evaluate a shell command supplied in the invitation.
|
||||
command = [str(Path(sys.executable).absolute()), "-I", "-m", "nanobot", "remote", "pair",
|
||||
request, "--config", str(config), "--port", str(port)]
|
||||
for option, value in (("--host", host or _default_host()),
|
||||
("--ssh-user", ssh_user or _default_ssh_user())):
|
||||
if value:
|
||||
command.extend([option, value])
|
||||
sudo = shutil.which("sudo")
|
||||
if os.getuid() == 0 or sudo is None:
|
||||
typer.echo("Ask the administrator to run this in nanobot's installation environment:")
|
||||
typer.echo(shlex.join(command))
|
||||
typer.echo("Do not make the config publicly readable.")
|
||||
raise typer.Exit(1)
|
||||
typer.echo("You may be asked for your server login password. You'll review device access next.")
|
||||
if not typer.confirm("Continue as server administrator?", default=False):
|
||||
typer.echo("Cancelled. No device was authorized. Run the pairing command again when ready.")
|
||||
raise typer.Exit(0)
|
||||
result = subprocess.run([sudo, "--", *command], check=False)
|
||||
if result.returncode:
|
||||
typer.echo("Pairing did not finish. Follow the message above, or ask your server administrator.\n"
|
||||
"To retry, run the pairing command again; get a new command if it has expired.", err=True)
|
||||
raise typer.Exit(result.returncode if result.returncode >= 0 else 1)
|
||||
|
||||
|
||||
@app.command()
|
||||
def pair(
|
||||
request: str = typer.Argument(help="Public pairing request copied from your local WebUI"),
|
||||
@@ -80,8 +113,14 @@ def pair(
|
||||
config = Path(candidates[choice - 1].config_path)
|
||||
else:
|
||||
config = Path(typer.prompt("Path to your nanobot config"))
|
||||
config = config.expanduser().resolve()
|
||||
details = metadata(config)
|
||||
config = config.expanduser().absolute()
|
||||
try:
|
||||
config = config.resolve()
|
||||
details = metadata(config)
|
||||
except (PermissionError, RemoteError) as exc:
|
||||
if not isinstance(exc, PermissionError) and str(exc) != "config_permission":
|
||||
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")
|
||||
if not host:
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""A regular cloud login can complete pairing without guessing a sudo command."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
from typer.testing import CliRunner
|
||||
|
||||
from nanobot.cli import remote
|
||||
from nanobot.webui import remote_pair_server
|
||||
from nanobot.webui.remote_pairing import PairStore, read_request
|
||||
from nanobot.webui.remote_ssh import RemoteError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def protected(monkeypatch, tmp_path):
|
||||
request = PairStore(tmp_path / "local").start()["command"].split()[-1]
|
||||
host_key = read_request(request).ssh_key
|
||||
config = tmp_path / "service account" / "config.json"
|
||||
monkeypatch.setattr(remote.sys, "platform", "linux")
|
||||
monkeypatch.setattr(remote.os, "getuid", lambda: 1001, raising=False)
|
||||
monkeypatch.setattr(remote, "_default_ssh_user", lambda: "ubuntu")
|
||||
monkeypatch.setattr(remote, "_default_host", lambda: "8.8.8.8")
|
||||
monkeypatch.setattr(remote.shutil, "which", lambda _: "/usr/bin/sudo")
|
||||
original_read = Path.read_text
|
||||
monkeypatch.setattr(Path, "read_text", lambda path, *a, **kw:
|
||||
host_key if path.name == "ssh_host_ed25519_key.pub"
|
||||
else original_read(path, *a, **kw))
|
||||
metadata = Mock(side_effect=RemoteError("config_permission"))
|
||||
authorize = Mock()
|
||||
run = Mock(return_value=SimpleNamespace(returncode=0))
|
||||
monkeypatch.setattr(remote_pair_server, "metadata", metadata)
|
||||
monkeypatch.setattr(remote_pair_server, "authorize", authorize)
|
||||
monkeypatch.setattr(remote.subprocess, "run", run)
|
||||
return SimpleNamespace(request=request, config=config, metadata=metadata, authorize=authorize,
|
||||
run=run, args=["pair", request, "--config", str(config)])
|
||||
|
||||
|
||||
def test_explicit_admin_consent_keeps_environment_config_and_login(protected, monkeypatch):
|
||||
python = str(protected.config.parent / ".venv" / "bin" / "python")
|
||||
monkeypatch.setattr(remote.sys, "executable", python)
|
||||
result = CliRunner().invoke(remote.app, protected.args, input="y\n")
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "Continue as server administrator?" in result.output
|
||||
assert "File permissions will not change" in result.output
|
||||
protected.run.assert_called_once_with([
|
||||
"/usr/bin/sudo", "--", python, "-I", "-m", "nanobot",
|
||||
"remote", "pair", protected.request, "--config", str(protected.config), "--port", "22",
|
||||
"--host", "8.8.8.8", "--ssh-user", "ubuntu",
|
||||
], check=False)
|
||||
protected.authorize.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", ["n\n", "\n", ""])
|
||||
def test_decline_or_closed_stdin_never_escalates(protected, answer):
|
||||
result = CliRunner().invoke(remote.app, protected.args, input=answer)
|
||||
assert result.exit_code in (0, 1)
|
||||
assert "Continue as server administrator?" in result.output
|
||||
protected.run.assert_not_called()
|
||||
protected.authorize.assert_not_called()
|
||||
|
||||
|
||||
def test_explicit_options_survive_sudo(protected):
|
||||
result = CliRunner().invoke(remote.app, protected.args + ["--host", "server.example",
|
||||
"--ssh-user", "deploy", "--port", "2222"], input="y\n")
|
||||
assert result.exit_code == 0
|
||||
argv = protected.run.call_args.args[0]
|
||||
assert argv[argv.index("--host") + 1] == "server.example"
|
||||
assert argv[argv.index("--ssh-user") + 1] == "deploy"
|
||||
assert argv[argv.index("--port") + 1] == "2222"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("root", [False, True])
|
||||
def test_missing_sudo_or_denied_root_has_manual_recovery_without_recursion(protected, monkeypatch, root):
|
||||
monkeypatch.setattr(remote.os, "getuid", lambda: 0 if root else 1001)
|
||||
if not root:
|
||||
monkeypatch.setattr(remote.shutil, "which", lambda _: None)
|
||||
result = CliRunner().invoke(remote.app, protected.args)
|
||||
assert result.exit_code == 1
|
||||
assert "Ask the administrator" in result.output
|
||||
assert "Do not make the config publicly readable" in result.output
|
||||
assert "Continue as server administrator?" not in result.output
|
||||
protected.run.assert_not_called()
|
||||
|
||||
|
||||
def test_sudo_failure_keeps_error_and_gives_retry(protected):
|
||||
protected.run.return_value.returncode = 1
|
||||
result = CliRunner().invoke(remote.app, protected.args, input="y\n")
|
||||
assert result.exit_code == 1
|
||||
assert "Pairing did not finish" in result.output
|
||||
assert "get a new command if it has expired" in result.output
|
||||
protected.authorize.assert_not_called()
|
||||
|
||||
|
||||
def test_other_config_error_does_not_offer_sudo(protected):
|
||||
protected.metadata.side_effect = RemoteError("pair_webui_auth_required")
|
||||
result = CliRunner().invoke(remote.app, protected.args)
|
||||
assert result.exit_code == 1
|
||||
assert "Continue as server administrator?" not in result.output
|
||||
protected.run.assert_not_called()
|
||||
|
||||
|
||||
def test_invalid_request_never_offers_sudo(protected):
|
||||
result = CliRunner().invoke(remote.app, ["pair", "not-a-request", "--config", str(protected.config)])
|
||||
assert result.exit_code == 1
|
||||
protected.metadata.assert_not_called()
|
||||
protected.run.assert_not_called()
|
||||
|
||||
|
||||
def test_readable_config_still_requires_device_authorization(protected):
|
||||
protected.metadata.side_effect = None
|
||||
protected.metadata.return_value = {"port": 8765}
|
||||
result = CliRunner().invoke(remote.app, protected.args + ["--host", "example.com"], input="n\n")
|
||||
assert result.exit_code == 1
|
||||
assert "Authorize this computer?" in result.output
|
||||
assert "Continue as server administrator?" not in result.output
|
||||
protected.run.assert_not_called()
|
||||
protected.authorize.assert_not_called()
|
||||
|
||||
|
||||
def test_expired_request_never_offers_sudo(protected, monkeypatch):
|
||||
from nanobot.webui import remote_pairing
|
||||
|
||||
now = remote_pairing.time.time()
|
||||
monkeypatch.setattr(remote_pairing.time, "time", lambda: now + 601)
|
||||
result = CliRunner().invoke(remote.app, protected.args)
|
||||
assert result.exit_code == 1
|
||||
assert "pair_expired" in result.output
|
||||
protected.run.assert_not_called()
|
||||
|
||||
|
||||
def test_unavailable_sudo_process_fails_without_authorizing(protected):
|
||||
protected.run.side_effect = subprocess.SubprocessError()
|
||||
result = CliRunner().invoke(remote.app, protected.args, input="y\n")
|
||||
assert result.exit_code == 1
|
||||
protected.authorize.assert_not_called()
|
||||
|
||||
|
||||
def test_discovered_service_config_is_carried_into_admin_retry(protected):
|
||||
protected.run.side_effect = [SimpleNamespace(stdout="NANOBOT_REMOTE:" + json.dumps({
|
||||
"hostname": "team", "incomplete": False, "candidates": [{"config_path": str(protected.config),
|
||||
"runtime_user": "nanobot", "service": "nanobot-team.service"}],
|
||||
})), SimpleNamespace(returncode=0)]
|
||||
result = CliRunner().invoke(remote.app, ["pair", protected.request], input="y\n")
|
||||
assert result.exit_code == 0, result.output
|
||||
argv = protected.run.call_args.args[0]
|
||||
assert argv[argv.index("--config") + 1] == str(protected.config)
|
||||
assert argv[argv.index("--ssh-user") + 1] == "ubuntu"
|
||||
assert protected.run.call_count == 2
|
||||
|
||||
|
||||
def test_protected_parent_directory_offers_same_recovery(protected, monkeypatch):
|
||||
original = Path.resolve
|
||||
def resolve(path, *args, **kwargs):
|
||||
if path == protected.config:
|
||||
raise PermissionError
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, "resolve", resolve)
|
||||
result = CliRunner().invoke(remote.app, protected.args, input="n\n")
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "Continue as server administrator?" in result.output
|
||||
protected.metadata.assert_not_called()
|
||||
protected.run.assert_not_called()
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Use existing SSH settings",
|
||||
"start": "Get pairing command",
|
||||
"runTitle": "1. Run on your server",
|
||||
"runHint": "Open the terminal in your cloud console. Paste this command and follow the prompts. The server also needs this version of nanobot.",
|
||||
"runHint": "Paste the command into your cloud terminal and follow the prompts. If asked, confirm administrator access to continue. The server needs this version of nanobot.",
|
||||
"command": "Pairing command",
|
||||
"copy": "Copy command",
|
||||
"copied": "Copied",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Usar ajustes SSH existentes",
|
||||
"start": "Obtener comando",
|
||||
"runTitle": "1. Ejecutar en el servidor",
|
||||
"runHint": "Abre el terminal de tu consola en la nube, pega el comando y sigue las indicaciones. El servidor también necesita esta versión de nanobot.",
|
||||
"runHint": "Pega el comando en la terminal de la nube y sigue las instrucciones. Si se solicita, confirma el acceso de administrador para continuar. El servidor necesita esta versión de nanobot.",
|
||||
"command": "Comando de emparejamiento",
|
||||
"copy": "Copiar comando",
|
||||
"copied": "Copiado",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Utiliser les réglages SSH",
|
||||
"start": "Obtenir la commande",
|
||||
"runTitle": "1. Exécuter sur le serveur",
|
||||
"runHint": "Ouvrez le terminal de votre console cloud, collez la commande et suivez les indications. Le serveur doit aussi utiliser cette version de nanobot.",
|
||||
"runHint": "Collez la commande dans le terminal cloud et suivez les instructions. Si nécessaire, confirmez l’accès administrateur pour continuer. Le serveur doit utiliser cette version de nanobot.",
|
||||
"command": "Commande d’association",
|
||||
"copy": "Copier la commande",
|
||||
"copied": "Copié",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Gunakan pengaturan SSH",
|
||||
"start": "Dapatkan perintah",
|
||||
"runTitle": "1. Jalankan di server",
|
||||
"runHint": "Buka terminal konsol cloud, tempel perintah, lalu ikuti petunjuknya. Server juga memerlukan versi nanobot yang mendukung fitur ini.",
|
||||
"runHint": "Tempel perintah di terminal cloud dan ikuti petunjuknya. Jika diminta, konfirmasikan akses administrator untuk melanjutkan. Server memerlukan versi nanobot ini.",
|
||||
"command": "Perintah pemasangan",
|
||||
"copy": "Salin perintah",
|
||||
"copied": "Disalin",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "既存の SSH 設定を使用",
|
||||
"start": "コマンドを取得",
|
||||
"runTitle": "1. サーバーで実行",
|
||||
"runHint": "クラウド管理画面の端末にコマンドを貼り付け、案内に従ってください。サーバーにもこの機能に対応した nanobot が必要です。",
|
||||
"runHint": "クラウド端末にコマンドを貼り付け、案内に従ってください。管理者権限を求められたら確認して続行します。サーバーにもこのバージョンの nanobot が必要です。",
|
||||
"command": "ペアリングコマンド",
|
||||
"copy": "コマンドをコピー",
|
||||
"copied": "コピーしました",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "기존 SSH 설정 사용",
|
||||
"start": "페어링 명령 받기",
|
||||
"runTitle": "1. 서버에서 실행",
|
||||
"runHint": "클라우드 콘솔의 터미널에 명령을 붙여넣고 안내를 따르세요. 서버에도 이 기능을 지원하는 nanobot 버전이 필요합니다.",
|
||||
"runHint": "클라우드 터미널에 명령을 붙여넣고 안내를 따르세요. 관리자 권한을 요청하면 확인하여 계속하세요. 서버에도 이 버전의 nanobot이 필요합니다.",
|
||||
"command": "페어링 명령",
|
||||
"copy": "명령 복사",
|
||||
"copied": "복사됨",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Usar configurações SSH",
|
||||
"start": "Obter comando",
|
||||
"runTitle": "1. Executar no servidor",
|
||||
"runHint": "Abra o terminal do console de nuvem, cole o comando e siga as instruções. O servidor também precisa desta versão do nanobot.",
|
||||
"runHint": "Cole o comando no terminal da nuvem e siga as instruções. Se solicitado, confirme o acesso de administrador para continuar. O servidor precisa desta versão do nanobot.",
|
||||
"command": "Comando de pareamento",
|
||||
"copy": "Copiar comando",
|
||||
"copied": "Copiado",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "Dùng cấu hình SSH có sẵn",
|
||||
"start": "Lấy lệnh ghép nối",
|
||||
"runTitle": "1. Chạy trên máy chủ",
|
||||
"runHint": "Mở terminal của bảng điều khiển đám mây, dán lệnh và làm theo hướng dẫn. Máy chủ cũng cần phiên bản nanobot hỗ trợ tính năng này.",
|
||||
"runHint": "Dán lệnh vào terminal đám mây và làm theo hướng dẫn. Nếu được yêu cầu, xác nhận quyền quản trị để tiếp tục. Máy chủ cần phiên bản nanobot này.",
|
||||
"command": "Lệnh ghép nối",
|
||||
"copy": "Sao chép lệnh",
|
||||
"copied": "Đã sao chép",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "使用已有 SSH 配置",
|
||||
"start": "获取配对命令",
|
||||
"runTitle": "1. 在服务器上运行",
|
||||
"runHint": "打开云控制台的终端,粘贴命令并按提示操作。服务器也需要安装支持此功能的 nanobot 版本。",
|
||||
"runHint": "在云控制台的终端粘贴命令,按提示操作。如果提示需要管理员权限,确认后即可继续。服务器也需安装当前版本的 nanobot。",
|
||||
"command": "配对命令",
|
||||
"copy": "复制命令",
|
||||
"copied": "已复制",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"useSSH": "使用既有 SSH 設定",
|
||||
"start": "取得配對指令",
|
||||
"runTitle": "1. 在伺服器上執行",
|
||||
"runHint": "開啟雲端控制台終端,貼上指令並依提示操作。伺服器也需要支援此功能的 nanobot 版本。",
|
||||
"runHint": "在雲端控制台的終端貼上命令,依提示操作。如需管理員權限,確認後即可繼續。伺服器也需安裝目前版本的 nanobot。",
|
||||
"command": "配對指令",
|
||||
"copy": "複製指令",
|
||||
"copied": "已複製",
|
||||
|
||||
Reference in new issue
Block a user