Files
napalm-ubiquiti/tests/test_client.py
T
Christian Manivong d4dac1e3c7 feat: controller client for UniFi OS and the standalone Network application
API key or local login, CSRF token, no redirects followed, a login rate
limit that backs off, MFA accounts refused with the way in, a wrong site
told apart from an empty one, paged Integration lists.

Refs NetOrk/netork#2787
2026-12-05 16:55:02 +01:00

245 lines
9.5 KiB
Python

"""The controller client: which API, how it logs in, how its failures read.
The HTTP transport is replaced by a fake session that answers by method and path;
no test opens a socket.
"""
from __future__ import annotations
import json
from typing import Any
import pytest
from napalm.base.exceptions import ConnectionException
from napalm_ubiquiti.client import (
NotFound,
RateLimited,
SiteNotFound,
UnifiClient,
UnifiError,
)
class FakeResponse:
def __init__(self, status: int, body: Any = None, headers: dict[str, str] | None = None) -> None:
self.status_code = status
self._body = body
self.headers = headers or {}
self.text = body if isinstance(body, str) else json.dumps(body)
def json(self) -> Any:
if isinstance(self._body, str):
raise ValueError("not json")
return self._body
class FakeSession:
def __init__(self, answers: dict[tuple[str, str], Any]) -> None:
self.answers = answers
self.sent: list[dict[str, Any]] = []
self.headers: dict[str, str] = {}
self.verify: Any = True
def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
path = url.split("://", 1)[1].split("/", 1)[1]
path = "/" + path
self.sent.append({"method": method, "path": path, "headers": dict(self.headers), **kwargs})
answer = self.answers.get((method, path))
if answer is None:
return FakeResponse(404, {"meta": {"rc": "error", "msg": "api.err.NotFound"}})
if callable(answer):
return answer(kwargs) # type: ignore[no-any-return]
return answer # type: ignore[no-any-return]
def ok(data: Any) -> FakeResponse:
return FakeResponse(200, {"meta": {"rc": "ok"}, "data": data})
def _client(answers: dict[tuple[str, str], Any], **kwargs: Any) -> tuple[UnifiClient, FakeSession]:
session = FakeSession(answers)
client = UnifiClient("https://192.0.2.1", session=session, **kwargs)
return client, session
class TestApiKey:
def test_the_key_goes_in_a_header_and_no_login_happens(self) -> None:
client, session = _client({("GET", "/proxy/network/api/s/default/stat/device"): ok([{"mac": "x"}])}, api_key="k3y")
client.login()
records = client.classic_get("default", "stat/device")
assert records == [{"mac": "x"}]
assert session.headers["X-API-KEY"] == "k3y"
assert [s["path"] for s in session.sent] == ["/proxy/network/api/s/default/stat/device"]
def test_redirects_are_never_followed(self) -> None:
client, session = _client({("GET", "/proxy/network/integration/v1/info"): FakeResponse(302, "", {"Location": "https://evil/"})}, api_key="k")
with pytest.raises(UnifiError, match="redirect"):
client.integration_get("info")
assert session.sent[0]["allow_redirects"] is False
def test_a_refused_key(self) -> None:
client, _ = _client({("GET", "/proxy/network/integration/v1/info"): FakeResponse(401, {"error": "unauthorized"})}, api_key="k")
with pytest.raises(ConnectionException, match="API key"):
client.integration_get("info")
class TestLogin:
def test_a_unifi_os_console_logs_in_and_keeps_the_csrf_token(self) -> None:
login = FakeResponse(200, {"username": "admin"}, {"X-CSRF-Token": "csrf-1"})
client, session = _client(
{
("POST", "/api/auth/login"): login,
("PUT", "/proxy/network/api/s/default/rest/device/abc"): ok([]),
},
username="admin",
password="pw",
)
client.login()
client.classic_write("PUT", "default", "rest/device/abc", {"port_overrides": []})
assert client.unifi_os is True
assert session.sent[0]["json"] == {"username": "admin", "password": "pw", "remember": True}
assert session.sent[1]["headers"]["X-CSRF-Token"] == "csrf-1"
def test_a_standalone_controller_falls_back_to_its_own_login(self) -> None:
client, session = _client(
{
("POST", "/api/login"): ok([]),
("GET", "/api/s/default/stat/device"): ok([]),
},
username="admin",
password="pw",
)
client.login()
client.classic_get("default", "stat/device")
assert client.unifi_os is False
assert [s["path"] for s in session.sent] == ["/api/auth/login", "/api/login", "/api/s/default/stat/device"]
def test_a_cloud_account_with_mfa_is_refused_with_the_way_in(self) -> None:
client, _ = _client({("POST", "/api/auth/login"): FakeResponse(499, {"code": "MFA_AUTH_REQUIRED"})}, username="me@example.com", password="pw")
with pytest.raises(ConnectionException, match="local admin|API key"):
client.login()
def test_wrong_credentials(self) -> None:
client, _ = _client({("POST", "/api/auth/login"): FakeResponse(401, {"code": "AUTHENTICATION_FAILED_INVALID_CREDENTIALS"})}, username="a", password="b")
with pytest.raises(ConnectionException, match="refused"):
client.login()
def test_the_login_rate_limit_backs_off_instead_of_retrying(self) -> None:
client, session = _client(
{("POST", "/api/auth/login"): FakeResponse(429, {"code": "AUTHENTICATION_FAILED_LIMIT_REACHED"}, {"Retry-After": "300"})},
username="a",
password="b",
)
with pytest.raises(RateLimited) as caught:
client.login()
assert caught.value.retry_after == 300
assert len(session.sent) == 1
def test_neither_key_nor_login(self) -> None:
client, _ = _client({})
with pytest.raises(ConnectionException, match="API key or"):
client.login()
class TestClassic:
def test_a_wrong_site_is_not_an_empty_controller(self) -> None:
answer = FakeResponse(401, {"meta": {"rc": "error", "msg": "api.err.NoSiteContext"}, "data": []})
client, _ = _client({("GET", "/proxy/network/api/s/nosuch/stat/device"): answer}, api_key="k")
with pytest.raises(SiteNotFound, match="nosuch"):
client.classic_get("nosuch", "stat/device")
def test_an_error_answer_raises(self) -> None:
answer = FakeResponse(400, {"meta": {"rc": "error", "msg": "api.err.Invalid"}, "data": []})
client, _ = _client({("GET", "/proxy/network/api/s/default/rest/portconf"): answer}, api_key="k")
with pytest.raises(UnifiError, match="api.err.Invalid"):
client.classic_get("default", "rest/portconf")
def test_a_missing_endpoint_is_not_found(self) -> None:
client, _ = _client({}, api_key="k")
with pytest.raises(NotFound):
client.classic_get("default", "rest/nothing")
def test_sites_come_from_self_sites(self) -> None:
client, _ = _client({("GET", "/proxy/network/api/self/sites"): ok([{"name": "default", "desc": "Default"}])}, api_key="k")
assert client.classic_sites() == [{"name": "default", "desc": "Default"}]
def test_a_server_error_names_the_status(self) -> None:
client, _ = _client({("GET", "/proxy/network/api/s/default/stat/device"): FakeResponse(502, "Bad Gateway")}, api_key="k")
with pytest.raises(UnifiError, match="502"):
client.classic_get("default", "stat/device")
class TestIntegration:
def test_pages_are_followed_to_the_total(self) -> None:
def page(kwargs: dict[str, Any]) -> FakeResponse:
offset = kwargs["params"]["offset"]
data = [{"n": offset + i} for i in range(2 if offset < 4 else 1)]
return FakeResponse(200, {"offset": offset, "limit": 2, "count": len(data), "totalCount": 5, "data": data})
client, session = _client({("GET", "/proxy/network/integration/v1/sites"): page}, api_key="k")
items = client.integration_list("sites")
assert [i["n"] for i in items] == [0, 1, 2, 3, 4]
assert [s["params"]["offset"] for s in session.sent] == [0, 2, 4]
assert session.sent[0]["params"]["limit"] == 200
def test_an_empty_page_stops_the_walk(self) -> None:
answer = FakeResponse(200, {"offset": 0, "limit": 200, "count": 0, "totalCount": 9, "data": []})
client, session = _client({("GET", "/proxy/network/integration/v1/sites"): answer}, api_key="k")
assert client.integration_list("sites") == []
assert len(session.sent) == 1
def test_the_application_version(self) -> None:
client, _ = _client({("GET", "/proxy/network/integration/v1/info"): FakeResponse(200, {"applicationVersion": "10.6.106"})}, api_key="k")
assert client.application_version() == (10, 6, 106)
def test_no_integration_api_on_a_standalone_controller(self) -> None:
client, _ = _client({("POST", "/api/login"): ok([])}, username="a", password="b")
client.login()
with pytest.raises(NotFound):
client.integration_get("info")
def test_an_endpoint_older_controllers_lack(self) -> None:
client, _ = _client({}, api_key="k")
with pytest.raises(NotFound):
client.integration_list("sites/x/networks")
class TestTransportErrors:
def test_an_unreachable_controller(self) -> None:
class Down(FakeSession):
def request(self, method: str, url: str, **kwargs: Any) -> FakeResponse:
import requests
raise requests.ConnectionError("refused")
client = UnifiClient("https://192.0.2.1", session=Down({}), api_key="k")
with pytest.raises(ConnectionException, match="192.0.2.1"):
client.integration_get("info")