driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 19s
driver / lowest (pull_request) Failing after 25s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Failing after 1m52s
driver / publish (pull_request) Skipped
A driver for Home Assistant OS and Supervised installs. It reaches the Supervisor through Home Assistant's WebSocket (supervisor/api) with an administrator's long-lived access token: no add-on, no SSH. Getters: facts, interfaces and addresses, host status (pending reboot, data disk), pending updates of Core, OS, Supervisor and add-ons, add-ons as services, running backups. Actions: apply updates, add-on start/stop/ restart and start at boot, refresh updates, reboot and shutdown. The fixtures are built from the Supervisor 2026.11.0 API source, not recorded; they are replaced once the first device is onboarded.
254 lines
7.7 KiB
Python
254 lines
7.7 KiB
Python
"""The WebSocket session with the socket replaced: what it sends, what it makes of answers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from napalm.base.exceptions import ConnectAuthError, ConnectionException
|
|
from napalm_device_types.tls_certificates import CertificateCheck, TlsCertificateMismatch
|
|
|
|
from napalm_homeassistant.transport import (
|
|
ConnectionLost,
|
|
HomeAssistantError,
|
|
Session,
|
|
start_session,
|
|
)
|
|
|
|
TOKEN = "token-123"
|
|
AUTH_REQUIRED = {"type": "auth_required", "ha_version": "2026.11.3"}
|
|
AUTH_OK = {"type": "auth_ok", "ha_version": "2026.11.3"}
|
|
CERT = b"certificate-der"
|
|
|
|
|
|
class FakeSocket:
|
|
def __init__(self, *inbound: Any) -> None:
|
|
self.inbound = list(inbound)
|
|
self.sent: list[dict[str, Any]] = []
|
|
self.timeouts: list[float | None] = []
|
|
self.closed = False
|
|
|
|
def send(self, text: str) -> None:
|
|
self.sent.append(json.loads(text))
|
|
|
|
def recv(self, timeout: float | None) -> str:
|
|
self.timeouts.append(timeout)
|
|
item = self.inbound.pop(0)
|
|
if isinstance(item, BaseException):
|
|
raise item
|
|
return item if isinstance(item, str) else json.dumps(item)
|
|
|
|
def close(self) -> None:
|
|
self.closed = True
|
|
|
|
|
|
def result(request_id: int, value: Any) -> dict[str, Any]:
|
|
return {"id": request_id, "type": "result", "success": True, "result": value}
|
|
|
|
|
|
def logged_in(*inbound: Any) -> tuple[Session, FakeSocket]:
|
|
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK, *inbound)
|
|
session = Session(socket, timeout=30.0)
|
|
session.authenticate(TOKEN)
|
|
return session, socket
|
|
|
|
|
|
# --- login -------------------------------------------------------------------------------
|
|
|
|
|
|
def test_login_sends_the_token_and_keeps_the_version() -> None:
|
|
session, socket = logged_in()
|
|
|
|
assert socket.sent == [{"type": "auth", "access_token": TOKEN}]
|
|
assert session.ha_version == "2026.11.3"
|
|
|
|
|
|
def test_a_refused_token_is_an_authentication_error_that_does_not_name_it() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, {"type": "auth_invalid", "message": "Invalid access token"})
|
|
|
|
with pytest.raises(ConnectAuthError) as raised:
|
|
Session(socket, timeout=30.0).authenticate(TOKEN)
|
|
|
|
assert "Invalid access token" in str(raised.value)
|
|
assert TOKEN not in str(raised.value)
|
|
|
|
|
|
def test_a_server_that_does_not_ask_for_a_login_is_refused_before_the_token_leaves() -> None:
|
|
socket = FakeSocket({"type": "hello"})
|
|
|
|
with pytest.raises(ConnectionException):
|
|
Session(socket, timeout=30.0).authenticate(TOKEN)
|
|
|
|
assert socket.sent == []
|
|
|
|
|
|
def test_an_unexpected_answer_to_the_login_is_a_connection_error() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, {"type": "something_else"})
|
|
|
|
with pytest.raises(ConnectionException):
|
|
Session(socket, timeout=30.0).authenticate(TOKEN)
|
|
|
|
|
|
# --- calls -------------------------------------------------------------------------------
|
|
|
|
|
|
def test_a_supervisor_call_is_numbered_and_answered_by_its_id() -> None:
|
|
session, socket = logged_in(
|
|
{"id": 1, "type": "event", "event": {}},
|
|
result(7, "someone else's"),
|
|
result(1, {"hostname": "ha-lab-01"}),
|
|
result(2, {"version": "18.4"}),
|
|
)
|
|
|
|
assert session.supervisor("/host/info") == {"hostname": "ha-lab-01"}
|
|
assert session.supervisor("/os/info") == {"version": "18.4"}
|
|
assert socket.sent[1:] == [
|
|
{"id": 1, "type": "supervisor/api", "endpoint": "/host/info", "method": "get"},
|
|
{"id": 2, "type": "supervisor/api", "endpoint": "/os/info", "method": "get"},
|
|
]
|
|
|
|
|
|
def test_a_call_with_data_sends_it() -> None:
|
|
session, socket = logged_in(result(1, {}))
|
|
|
|
session.supervisor("/addons/core_samba/options", "post", {"boot": "auto"})
|
|
|
|
assert socket.sent[1]["data"] == {"boot": "auto"}
|
|
assert socket.sent[1]["method"] == "post"
|
|
|
|
|
|
def test_a_long_call_lifts_home_assistants_limit_and_waits_as_long_as_asked() -> None:
|
|
session, socket = logged_in(result(1, {}))
|
|
|
|
session.supervisor("/core/update", "post", {"backup": False}, wait=1800.0)
|
|
|
|
assert socket.sent[1]["timeout"] is None
|
|
assert socket.timeouts[-1] == 1800.0
|
|
|
|
|
|
def test_a_short_call_waits_the_session_timeout() -> None:
|
|
session, socket = logged_in(result(1, {}))
|
|
|
|
session.supervisor("/host/info")
|
|
|
|
assert "timeout" not in socket.sent[1]
|
|
assert socket.timeouts[-1] == 30.0
|
|
|
|
|
|
def test_a_refused_call_raises_with_home_assistants_code() -> None:
|
|
session, _ = logged_in(
|
|
{
|
|
"id": 1,
|
|
"type": "result",
|
|
"success": False,
|
|
"error": {"code": "unknown_command", "message": "Unknown command."},
|
|
}
|
|
)
|
|
|
|
with pytest.raises(HomeAssistantError) as raised:
|
|
session.supervisor("/host/info")
|
|
|
|
assert raised.value.code == "unknown_command"
|
|
assert raised.value.message == "Unknown command."
|
|
|
|
|
|
def test_a_refusal_without_details_still_raises() -> None:
|
|
session, _ = logged_in({"id": 1, "type": "result", "success": False})
|
|
|
|
with pytest.raises(HomeAssistantError) as raised:
|
|
session.supervisor("/host/info")
|
|
|
|
assert raised.value.code == "unknown_error"
|
|
|
|
|
|
def test_no_answer_in_time_is_a_connection_error() -> None:
|
|
session, _ = logged_in(TimeoutError())
|
|
|
|
with pytest.raises(ConnectionException, match="30"):
|
|
session.supervisor("/host/info")
|
|
|
|
|
|
def test_a_closed_connection_is_reported_as_lost() -> None:
|
|
session, _ = logged_in(ConnectionLost("closed"))
|
|
|
|
with pytest.raises(ConnectionLost):
|
|
session.supervisor("/host/info")
|
|
|
|
|
|
def test_an_answer_that_is_no_json_is_a_connection_error() -> None:
|
|
session, _ = logged_in("<html>")
|
|
|
|
with pytest.raises(ConnectionException):
|
|
session.supervisor("/host/info")
|
|
|
|
|
|
def test_close_closes_the_socket() -> None:
|
|
session, socket = logged_in()
|
|
|
|
session.close()
|
|
|
|
assert socket.closed
|
|
|
|
|
|
# --- certificate -------------------------------------------------------------------------
|
|
|
|
|
|
def test_a_certificate_other_than_the_trusted_one_is_refused_before_the_token_leaves() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
|
|
seen: list[dict[str, Any]] = []
|
|
check = CertificateCheck(
|
|
{"tls_fingerprints": {"8123": "00" * 32}, "tls_certificate_observer": seen.append},
|
|
"192.0.2.21",
|
|
8123,
|
|
)
|
|
|
|
with pytest.raises(TlsCertificateMismatch):
|
|
start_session(socket, TOKEN, timeout=30.0, check=check, certificate=CERT)
|
|
|
|
assert socket.sent == []
|
|
assert socket.closed
|
|
assert seen[0]["accepted"] is False
|
|
|
|
|
|
def test_the_trusted_certificate_is_reported_once_the_login_stands() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
|
|
seen: list[dict[str, Any]] = []
|
|
expected = hashlib.sha256(CERT).hexdigest()
|
|
check = CertificateCheck(
|
|
{"tls_fingerprints": {"8123": expected}, "tls_certificate_observer": seen.append},
|
|
"192.0.2.21",
|
|
8123,
|
|
)
|
|
|
|
session = start_session(socket, TOKEN, timeout=30.0, check=check, certificate=CERT)
|
|
|
|
assert session.ha_version == "2026.11.3"
|
|
assert seen[0]["accepted"] is True
|
|
|
|
|
|
def test_a_plain_connection_logs_in_without_a_certificate() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, AUTH_OK)
|
|
|
|
session = start_session(socket, TOKEN, timeout=30.0)
|
|
|
|
assert socket.sent == [{"type": "auth", "access_token": TOKEN}]
|
|
assert session.ha_version == "2026.11.3"
|
|
|
|
|
|
def test_a_failed_login_closes_the_socket() -> None:
|
|
socket = FakeSocket(AUTH_REQUIRED, {"type": "auth_invalid", "message": "no"})
|
|
|
|
with pytest.raises(ConnectAuthError):
|
|
start_session(socket, TOKEN, timeout=30.0)
|
|
|
|
assert socket.closed
|
|
|
|
|
|
def test_an_answer_that_is_no_object_is_a_connection_error() -> None:
|
|
session, _ = logged_in("[1, 2]")
|
|
|
|
with pytest.raises(ConnectionException):
|
|
session.supervisor("/host/info")
|