Files
napalm-ubiquiti/tests/test_connection.py
T
Christian Manivong 1aaa8587d0 feat: open a controller with its certificate pinned
The controller's certificate is trusted on first use and pinned for the
session before any login. An api_token profile's secret is the API key;
otherwise a local admin's login, separate or the driver's own.
2026-12-05 16:59:54 +01:00

130 lines
4.4 KiB
Python

"""Reaching a controller: its address, the credentials netOrk hands over, its certificate."""
from __future__ import annotations
from typing import Any
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
from napalm_ubiquiti import connection
from napalm_ubiquiti.connection import (
ControllerLogin,
controller_login,
host_and_port,
open_controller,
)
class TestAddress:
def test_a_bare_host_is_https_on_443(self) -> None:
assert host_and_port("https://unifi.example") == ("unifi.example", 443)
def test_a_standalone_controller_on_8443(self) -> None:
assert host_and_port("https://192.0.2.5:8443") == ("192.0.2.5", 8443)
def test_an_ipv6_address(self) -> None:
assert host_and_port("https://[2001:db8::1]:8443") == ("2001:db8::1", 8443)
class TestLogin:
def test_the_secret_of_an_api_token_profile_is_the_key(self) -> None:
login = controller_login("", "", {"token_name": "netork", "token_value": "s3cret"})
assert login == ControllerLogin(api_key="s3cret", username="", password="")
def test_api_secret_counts_as_the_key_too(self) -> None:
login = controller_login("", "", {"api_key": "netork", "api_secret": "s3cret"})
assert login.api_key == "s3cret"
def test_without_a_key_the_login_is_used(self) -> None:
assert controller_login("admin", "pw", {}) == ControllerLogin("", "admin", "pw")
def test_a_separate_controller_login_wins(self) -> None:
args = {"controller_username": "netork", "controller_password": "pw2"}
assert controller_login("ubnt", "ssh-pw", args) == ControllerLogin("", "netork", "pw2")
class FakeSession:
def __init__(self) -> None:
self.headers: dict[str, str] = {}
self.verify: Any = True
self.mounted: list[str] = []
def mount(self, prefix: str, adapter: Any) -> None:
self.mounted.append(prefix)
@pytest.fixture
def handshake(monkeypatch: pytest.MonkeyPatch) -> list[CertificateCheck]:
"""The TLS handshake replaced: every server presents the certificate ``b"der"``."""
checks: list[CertificateCheck] = []
def verify_server(self: CertificateCheck, timeout: float, **_: Any) -> Any:
checks.append(self)
return self.verify(b"der")
monkeypatch.setattr(CertificateCheck, "verify_server", verify_server)
return checks
class TestOpen:
def test_the_certificate_is_checked_pinned_and_reported(
self, handshake: list[CertificateCheck]
) -> None:
seen: list[dict[str, Any]] = []
session = FakeSession()
client = open_controller(
"https://192.0.2.1",
ControllerLogin("k3y", "", ""),
{"tls_certificate_observer": seen.append},
timeout=5,
session=session,
)
assert (handshake[0].host, handshake[0].port) == ("192.0.2.1", 443)
assert session.mounted == ["https://"]
assert session.verify is False
assert seen[0]["accepted"] is True
assert client.unifi_os is True
def test_a_changed_certificate_is_refused_before_the_login(
self, handshake: list[CertificateCheck]
) -> None:
args = {"tls_fingerprints": {"443": "AA" * 32}}
with pytest.raises(TlsCertificateMismatch):
open_controller(
"https://192.0.2.1", ControllerLogin("", "a", "b"), args, 5, FakeSession()
)
def test_ca_verification_on_request(self, handshake: list[CertificateCheck]) -> None:
session = FakeSession()
open_controller(
"https://192.0.2.1", ControllerLogin("k", "", ""), {"ssl_verify": True}, 5, session
)
assert session.verify is True
def test_plain_http_is_refused(self) -> None:
with pytest.raises(ConnectionException, match="https"):
open_controller("http://192.0.2.1", ControllerLogin("k", "", ""), {}, 5, FakeSession())
def test_the_login_runs_on_the_pinned_session(
self, handshake: list[CertificateCheck], monkeypatch: pytest.MonkeyPatch
) -> None:
logins: list[Any] = []
monkeypatch.setattr(
connection.UnifiClient, "login", lambda self: logins.append(self.session)
)
session = FakeSession()
open_controller("https://192.0.2.1", ControllerLogin("", "a", "b"), {}, 5, session)
assert logins == [session]