"""The SSH shell to a UniFi device: verified host key, one command at a time. paramiko's client is replaced by a fake; no test opens a socket. """ from __future__ import annotations import io from typing import Any import paramiko import pytest from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from napalm.base.exceptions import CommandErrorException, ConnectionException from napalm_device_types.ssh_host_keys import HostKeyObservation, SshHostKey, SshHostKeyMismatch from napalm_ubiquiti.ssh import SshShell, load_private_key class FakeKey: def get_name(self) -> str: return "ssh-ed25519" def get_base64(self) -> str: return "AAAAC3NzaC1lZDI1NTE5AAAAIGZha2U=" class FakeTransport: def get_remote_server_key(self) -> FakeKey: return FakeKey() class FakeChannel: def __init__(self, status: int) -> None: self.status = status def recv_exit_status(self) -> int: return self.status class FakeStream(io.BytesIO): def __init__(self, data: bytes, status: int = 0) -> None: super().__init__(data) self.channel = FakeChannel(status) class FakeClient: def __init__(self, answers: dict[str, tuple[int, str, str]] | None = None) -> None: self.answers = answers or {} self.connected: dict[str, Any] = {} self.closed = False self.policy: Any = None def set_missing_host_key_policy(self, policy: Any) -> None: self.policy = policy def get_host_keys(self) -> Any: return paramiko.HostKeys() def connect(self, **kwargs: Any) -> None: if kwargs.get("password") == "wrong": raise paramiko.AuthenticationException("Authentication failed.") if kwargs.get("password") == "down": raise TimeoutError("timed out") self.connected = kwargs def get_transport(self) -> FakeTransport: return FakeTransport() def exec_command(self, command: str, timeout: float | None = None) -> tuple[Any, Any, Any]: status, out, err = self.answers.get(command, (127, "", f"sh: {command}: not found")) return None, FakeStream(out.encode(), status), FakeStream(err.encode()) def close(self) -> None: self.closed = True def _shell(client: FakeClient, **kwargs: Any) -> SshShell: return SshShell("192.0.2.10", username="ubnt", client_factory=lambda: client, **kwargs) class TestConnect: def test_a_password_login_without_agent_or_key_files(self) -> None: client = FakeClient() _shell(client, password="pw").open() assert client.connected["hostname"] == "192.0.2.10" assert client.connected["port"] == 22 assert client.connected["username"] == "ubnt" assert client.connected["password"] == "pw" assert client.connected["allow_agent"] is False assert client.connected["look_for_keys"] is False def test_the_host_key_seen_is_reported(self) -> None: seen: list[dict[str, Any]] = [] client = FakeClient() _shell(client, password="pw", optional_args={"ssh_host_key_observer": seen.append}).open() assert seen[0]["seen"]["key_type"] == "ssh-ed25519" assert seen[0]["accepted"] is True def test_a_refused_login_is_a_connection_error(self) -> None: with pytest.raises(ConnectionException, match="192.0.2.10"): _shell(FakeClient(), password="wrong").open() def test_an_unreachable_device_is_a_connection_error(self) -> None: client = FakeClient() with pytest.raises(ConnectionException, match="timed out"): _shell(client, password="down").open() assert client.closed is True def test_a_changed_host_key_is_refused_and_nothing_stays_open(self) -> None: class Refusing(FakeClient): def connect(self, **kwargs: Any) -> None: raise SshHostKeyMismatch( HostKeyObservation("192.0.2.10", 22, SshHostKey("ssh-rsa", "AAAA"), None) ) client = Refusing() with pytest.raises(SshHostKeyMismatch): _shell(client, password="pw").open() assert client.closed is True def test_no_password_and_no_key(self) -> None: with pytest.raises(ConnectionException, match="password or a private key"): _shell(FakeClient()).open() def test_running_before_opening(self) -> None: with pytest.raises(ConnectionException, match="not open"): _shell(FakeClient(), password="pw").run("mca-dump") def test_close_closes_the_client_once(self) -> None: client = FakeClient() shell = _shell(client, password="pw") shell.open() shell.close() shell.close() assert client.closed is True class TestRun: def test_the_output_of_a_command(self) -> None: client = FakeClient({"mca-dump": (0, '{"mac": "x"}', "")}) shell = _shell(client, password="pw") shell.open() assert shell.run("mca-dump") == '{"mac": "x"}' def test_a_failing_command_names_its_status_and_error(self) -> None: shell = _shell(FakeClient(), password="pw") shell.open() with pytest.raises(CommandErrorException, match="127.*not found"): shell.run("lldpcli show neighbors") class TestPrivateKey: def test_an_ed25519_key(self) -> None: text = Ed25519PrivateKey.generate().private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption(), ) assert load_private_key(text.decode()).get_name() == "ssh-ed25519" def test_an_rsa_key(self) -> None: text = io.StringIO() paramiko.RSAKey.generate(1024).write_private_key(text) assert load_private_key(text.getvalue()).get_name() == "ssh-rsa" def test_garbage_is_a_connection_error(self) -> None: with pytest.raises(ConnectionException, match="private key"): load_private_key("not a key") def test_a_key_login_hands_paramiko_the_key(self) -> None: text = io.StringIO() paramiko.RSAKey.generate(1024).write_private_key(text) client = FakeClient() _shell(client, private_key=text.getvalue()).open() assert client.connected["pkey"].get_name() == "ssh-rsa" assert client.connected["password"] is None