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
This commit is contained in:
1 parent
380759ae50
commit
d4dac1e3c7
2 files changed
+465
No files matched your search
@@ -0,0 +1,221 @@
|
||||
"""One HTTP session with a UniFi Network controller.
|
||||
|
||||
A UniFi OS console (UDM, UCG, Cloud Key Gen2+, UniFi OS Server) serves the
|
||||
Network application under ``/proxy/network``: the documented Integration API at
|
||||
``/proxy/network/integration/v1`` and the classic API at
|
||||
``/proxy/network/api/s/<site>/...``. An API key (``X-API-KEY``, Network 9.0.108
|
||||
and later) opens both. A standalone Network application (no UniFi OS) has only the
|
||||
classic API at ``/api/s/<site>/...`` and only a local login.
|
||||
|
||||
Redirects are never followed: a key must not travel to wherever a 302 points.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from napalm.base.exceptions import ConnectionException
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
UNIFI_OS_LOGIN = "/api/auth/login"
|
||||
STANDALONE_LOGIN = "/api/login"
|
||||
UNIFI_OS_CLASSIC = "/proxy/network/api"
|
||||
STANDALONE_CLASSIC = "/api"
|
||||
INTEGRATION = "/proxy/network/integration/v1"
|
||||
CSRF_HEADER = "X-CSRF-Token"
|
||||
CSRF_UPDATED = "X-Updated-Csrf-Token"
|
||||
KEY_HEADER = "X-API-KEY"
|
||||
PAGE_LIMIT = 200
|
||||
DEFAULT_TIMEOUT = 30.0
|
||||
DEFAULT_RETRY_AFTER = 300
|
||||
MFA_STATUS = 499
|
||||
NO_SITE = "api.err.NoSiteContext"
|
||||
|
||||
|
||||
class UnifiError(Exception):
|
||||
"""The controller answered, but not with what was asked for."""
|
||||
|
||||
|
||||
class NotFound(UnifiError):
|
||||
"""The endpoint does not exist here: an older controller, or no Integration API."""
|
||||
|
||||
|
||||
class SiteNotFound(UnifiError):
|
||||
"""The controller has no site by that name (``api.err.NoSiteContext``)."""
|
||||
|
||||
|
||||
class RateLimited(ConnectionException): # type: ignore[misc]
|
||||
"""The controller refuses logins for a while; retrying at once prolongs that."""
|
||||
|
||||
def __init__(self, message: str, retry_after: int) -> None:
|
||||
super().__init__(message)
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
def _error_text(response: Any) -> str:
|
||||
try:
|
||||
body = response.json()
|
||||
except ValueError:
|
||||
return str(response.text or "")[:200]
|
||||
if isinstance(body, dict):
|
||||
meta = body.get("meta") or {}
|
||||
return str(meta.get("msg") or body.get("code") or body.get("message") or body)
|
||||
return str(body)[:200]
|
||||
|
||||
|
||||
class UnifiClient:
|
||||
"""A session with the controller at *base_url* (``https://host[:port]``)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
*,
|
||||
api_key: str = "",
|
||||
username: str = "",
|
||||
password: str = "",
|
||||
session: Any = None,
|
||||
timeout: float = DEFAULT_TIMEOUT,
|
||||
) -> None:
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.api_key = api_key
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.timeout = timeout
|
||||
self.session = session if session is not None else requests.Session()
|
||||
#: A key exists only on UniFi OS; a login tells the two apart.
|
||||
self.unifi_os = bool(api_key)
|
||||
if api_key:
|
||||
self.session.headers[KEY_HEADER] = api_key
|
||||
|
||||
# -- transport ---------------------------------------------------------
|
||||
|
||||
def _send(self, method: str, path: str, **kwargs: Any) -> Any:
|
||||
try:
|
||||
response = self.session.request(
|
||||
method,
|
||||
f"{self.base_url}{path}",
|
||||
timeout=self.timeout,
|
||||
allow_redirects=False,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise ConnectionException(f"{self.base_url}: {exc}") from exc
|
||||
token = response.headers.get(CSRF_UPDATED) or response.headers.get(CSRF_HEADER)
|
||||
if token:
|
||||
self.session.headers[CSRF_HEADER] = token
|
||||
return response
|
||||
|
||||
def _check(self, response: Any, path: str) -> Any:
|
||||
status = response.status_code
|
||||
if 300 <= status < 400:
|
||||
raise UnifiError(f"{self.base_url}{path}: answered with a redirect; not followed")
|
||||
if status == 404:
|
||||
raise NotFound(f"{self.base_url}{path}: not found")
|
||||
text = _error_text(response)
|
||||
if NO_SITE in text:
|
||||
raise SiteNotFound(f"{self.base_url}: no site by that name ({path})")
|
||||
if status in (401, 403):
|
||||
what = "the API key" if self.api_key else "the session"
|
||||
raise ConnectionException(f"{self.base_url}: refused {what} ({status} {text})")
|
||||
if status >= 400:
|
||||
raise UnifiError(f"{self.base_url}{path}: {status} {text}")
|
||||
return response.json()
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
||||
return self._check(self._send(method, path, **kwargs), path)
|
||||
|
||||
# -- login -------------------------------------------------------------
|
||||
|
||||
def login(self) -> None:
|
||||
"""Log in with the username and password; with an API key there is nothing to do."""
|
||||
if self.api_key:
|
||||
return
|
||||
if not (self.username and self.password):
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: give an API key or a local admin's username and password"
|
||||
)
|
||||
body = {"username": self.username, "password": self.password}
|
||||
response = self._send("POST", UNIFI_OS_LOGIN, json={**body, "remember": True})
|
||||
if response.status_code == 404:
|
||||
response = self._send("POST", STANDALONE_LOGIN, json=body)
|
||||
self._check_login(response)
|
||||
self.unifi_os = False
|
||||
csrf = getattr(self.session, "cookies", {}).get("csrf_token")
|
||||
if csrf:
|
||||
self.session.headers[CSRF_HEADER] = csrf
|
||||
return
|
||||
self._check_login(response)
|
||||
self.unifi_os = True
|
||||
|
||||
def _check_login(self, response: Any) -> None:
|
||||
status = response.status_code
|
||||
if status == 429:
|
||||
wait = int(response.headers.get("Retry-After") or DEFAULT_RETRY_AFTER)
|
||||
raise RateLimited(f"{self.base_url}: too many logins; wait {wait} s", wait)
|
||||
if status == MFA_STATUS:
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: this account needs multi-factor authentication; "
|
||||
"use a local admin account or an API key"
|
||||
)
|
||||
if status >= 400:
|
||||
raise ConnectionException(
|
||||
f"{self.base_url}: login refused ({status} {_error_text(response)})"
|
||||
)
|
||||
|
||||
# -- classic API -------------------------------------------------------
|
||||
|
||||
def _classic(self, path: str) -> str:
|
||||
return f"{UNIFI_OS_CLASSIC if self.unifi_os else STANDALONE_CLASSIC}{path}"
|
||||
|
||||
def _classic_data(self, body: Any, path: str) -> list[Any]:
|
||||
meta = (body.get("meta") or {}) if isinstance(body, dict) else {}
|
||||
if meta.get("rc") == "error":
|
||||
message = str(meta.get("msg") or "")
|
||||
if message == NO_SITE:
|
||||
raise SiteNotFound(f"{self.base_url}: no site by that name ({path})")
|
||||
raise UnifiError(f"{self.base_url}{path}: {message}")
|
||||
return list(body.get("data") or []) if isinstance(body, dict) else []
|
||||
|
||||
def classic_get(self, site: str, endpoint: str) -> list[Any]:
|
||||
"""``GET /api/s/<site>/<endpoint>``: the ``data`` list."""
|
||||
path = self._classic(f"/s/{site}/{endpoint}")
|
||||
return self._classic_data(self._request("GET", path), path)
|
||||
|
||||
def classic_write(self, method: str, site: str, endpoint: str, body: Any) -> list[Any]:
|
||||
"""``POST``/``PUT``/``DELETE`` on the classic API: the ``data`` list it returns."""
|
||||
path = self._classic(f"/s/{site}/{endpoint}")
|
||||
return self._classic_data(self._request(method, path, json=body), path)
|
||||
|
||||
def classic_sites(self) -> list[Any]:
|
||||
"""The sites the account can see (``/api/self/sites``)."""
|
||||
path = self._classic("/self/sites")
|
||||
return self._classic_data(self._request("GET", path), path)
|
||||
|
||||
# -- Integration API ---------------------------------------------------
|
||||
|
||||
def _integration(self, endpoint: str) -> str:
|
||||
if not self.unifi_os:
|
||||
raise NotFound(f"{self.base_url}: a standalone controller has no Integration API")
|
||||
return f"{INTEGRATION}/{endpoint}"
|
||||
|
||||
def integration_get(self, endpoint: str, params: dict[str, Any] | None = None) -> Any:
|
||||
"""``GET /v1/<endpoint>`` of the Integration API."""
|
||||
return self._request("GET", self._integration(endpoint), params=params)
|
||||
|
||||
def integration_list(self, endpoint: str) -> list[Any]:
|
||||
"""Every item of a paged Integration API list."""
|
||||
items: list[Any] = []
|
||||
while True:
|
||||
page = self.integration_get(endpoint, {"offset": len(items), "limit": PAGE_LIMIT})
|
||||
data = list(page.get("data") or [])
|
||||
items.extend(data)
|
||||
if not data or len(items) >= int(page.get("totalCount") or 0):
|
||||
return items
|
||||
|
||||
def application_version(self) -> tuple[int, ...]:
|
||||
"""The Network application's version, e.g. ``(10, 6, 106)``."""
|
||||
version = str(self.integration_get("info").get("applicationVersion") or "")
|
||||
return tuple(int(part) for part in version.split(".") if part.isdigit())
|
||||
@@ -0,0 +1,244 @@
|
||||
"""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")
|
||||
Reference in new issue
Block a user