From 820e56adb775e352de75abeb9be7b272113769a7 Mon Sep 17 00:00:00 2001 From: Apoorva Verma <76636952+apoorva-01@users.noreply.github.com> Date: Fri, 23 Oct 2026 03:19:29 +0530 Subject: [PATCH] Migrate ubus from DeviceScanner to ScannerEntity and add config flow (#175799) Co-authored-by: Joostlek Co-authored-by: Claude Opus 5.5 --- homeassistant/components/ubus/__init__.py | 22 +- homeassistant/components/ubus/config_flow.py | 101 +++++++ homeassistant/components/ubus/const.py | 7 + homeassistant/components/ubus/coordinator.py | 163 ++++++++++++ .../components/ubus/device_tracker.py | 247 +++++++----------- homeassistant/components/ubus/manifest.json | 2 + homeassistant/components/ubus/strings.json | 43 +++ homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 2 +- tests/components/ubus/__init__.py | 1 + tests/components/ubus/conftest.py | 97 +++++++ tests/components/ubus/test_config_flow.py | 190 ++++++++++++++ tests/components/ubus/test_device_tracker.py | 101 +++++++ tests/components/ubus/test_init.py | 88 +++++++ 14 files changed, 909 insertions(+), 156 deletions(-) create mode 100644 homeassistant/components/ubus/config_flow.py create mode 100644 homeassistant/components/ubus/const.py create mode 100644 homeassistant/components/ubus/coordinator.py create mode 100644 homeassistant/components/ubus/strings.json create mode 100644 tests/components/ubus/__init__.py create mode 100644 tests/components/ubus/conftest.py create mode 100644 tests/components/ubus/test_config_flow.py create mode 100644 tests/components/ubus/test_device_tracker.py create mode 100644 tests/components/ubus/test_init.py diff --git a/homeassistant/components/ubus/__init__.py b/homeassistant/components/ubus/__init__.py index 227825ac7c0b..c26ff9e10667 100644 --- a/homeassistant/components/ubus/__init__.py +++ b/homeassistant/components/ubus/__init__.py @@ -1 +1,21 @@ -"""The ubus component.""" +"""The OpenWrt (ubus) integration.""" + +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant + +from .coordinator import UbusConfigEntry, UbusDataUpdateCoordinator + +PLATFORMS = [Platform.DEVICE_TRACKER] + + +async def async_setup_entry(hass: HomeAssistant, entry: UbusConfigEntry) -> None: + """Set up ubus from a config entry.""" + coordinator = UbusDataUpdateCoordinator(hass, entry) + await coordinator.async_config_entry_first_refresh() + entry.runtime_data = coordinator + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + +async def async_unload_entry(hass: HomeAssistant, entry: UbusConfigEntry) -> None: + """Unload a config entry.""" + await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) diff --git a/homeassistant/components/ubus/config_flow.py b/homeassistant/components/ubus/config_flow.py new file mode 100644 index 000000000000..ef6b032d5eb7 --- /dev/null +++ b/homeassistant/components/ubus/config_flow.py @@ -0,0 +1,101 @@ +"""Config flow for the OpenWrt (ubus) integration.""" + +from typing import Any, override + +from openwrt.ubus import Ubus +import probatio + +from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.helpers.selector import ( + SelectSelector, + SelectSelectorConfig, + SelectSelectorMode, +) + +from .const import CONF_DHCP_SOFTWARE, DEFAULT_DHCP_SOFTWARE, DHCP_SOFTWARES, DOMAIN + +STEP_USER_DATA_SCHEMA = probatio.Schema( + { + probatio.Required(CONF_HOST): str, + probatio.Required(CONF_USERNAME): str, + probatio.Required(probatio.Secret(CONF_PASSWORD)): str, + probatio.Required( + CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE + ): SelectSelector( + SelectSelectorConfig( + options=DHCP_SOFTWARES, + translation_key="dhcp_software", + mode=SelectSelectorMode.DROPDOWN, + ) + ), + } +) + + +def validate_connection(data: dict[str, Any]) -> None: + """Validate that we can log in to the router with the given configuration.""" + ubus = Ubus( + f"http://{data[CONF_HOST]}/ubus", + data[CONF_USERNAME], + data[CONF_PASSWORD], + ) + try: + session_id = ubus.connect() + except PermissionError as err: + raise InvalidAuth from err + except (ConnectionError, TypeError) as err: + # openwrt-ubus-rpc raises TypeError when the HTTP request itself fails. + raise CannotConnect from err + if session_id is None: + raise InvalidAuth + + +class UbusConfigFlow(ConfigFlow, domain=DOMAIN): + """Handle a config flow for OpenWrt (ubus).""" + + VERSION = 1 + + @override + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle the initial step.""" + errors: dict[str, str] = {} + if user_input is not None: + self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]}) + try: + await self.hass.async_add_executor_job(validate_connection, user_input) + except CannotConnect: + errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" + else: + return self.async_create_entry( + title=user_input[CONF_HOST], data=user_input + ) + + return self.async_show_form( + step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors + ) + + async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult: + """Import a configuration from configuration.yaml.""" + self._async_abort_entries_match({CONF_HOST: import_data[CONF_HOST]}) + + try: + await self.hass.async_add_executor_job(validate_connection, import_data) + except CannotConnect: + return self.async_abort(reason="cannot_connect") + except InvalidAuth: + return self.async_abort(reason="invalid_auth") + + return self.async_create_entry(title=import_data[CONF_HOST], data=import_data) + + +class CannotConnect(Exception): + """Error to indicate we cannot connect to the router.""" + + +class InvalidAuth(Exception): + """Error to indicate the credentials are invalid.""" diff --git a/homeassistant/components/ubus/const.py b/homeassistant/components/ubus/const.py new file mode 100644 index 000000000000..11414dfbf809 --- /dev/null +++ b/homeassistant/components/ubus/const.py @@ -0,0 +1,7 @@ +"""Constants for the OpenWrt (ubus) integration.""" + +DOMAIN = "ubus" + +CONF_DHCP_SOFTWARE = "dhcp_software" +DEFAULT_DHCP_SOFTWARE = "dnsmasq" +DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] diff --git a/homeassistant/components/ubus/coordinator.py b/homeassistant/components/ubus/coordinator.py new file mode 100644 index 000000000000..52dc217a4a1a --- /dev/null +++ b/homeassistant/components/ubus/coordinator.py @@ -0,0 +1,163 @@ +"""DataUpdateCoordinator for the OpenWrt (ubus) integration.""" + +from datetime import timedelta +import logging +from typing import override + +from openwrt.ubus import Ubus + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed + +from .const import CONF_DHCP_SOFTWARE, DOMAIN + +_LOGGER = logging.getLogger(__name__) + +UPDATE_INTERVAL = timedelta(seconds=30) + +type UbusConfigEntry = ConfigEntry[UbusDataUpdateCoordinator] + + +class UbusDataUpdateCoordinator(DataUpdateCoordinator[dict[str, str | None]]): + """Fetch the authorized wireless clients from an OpenWrt router over ubus.""" + + config_entry: UbusConfigEntry + + def __init__(self, hass: HomeAssistant, config_entry: UbusConfigEntry) -> None: + """Initialize the coordinator from a config entry.""" + self.host: str = config_entry.data[CONF_HOST] + self.dhcp_software: str = config_entry.data[CONF_DHCP_SOFTWARE] + self.ubus = Ubus( + f"http://{self.host}/ubus", + config_entry.data[CONF_USERNAME], + config_entry.data[CONF_PASSWORD], + ) + self._hostapd: list[str] = [] + self._leasefile: str | None = None + self._mac2name: dict[str, str] | None = None + + super().__init__( + hass, + _LOGGER, + config_entry=config_entry, + name=f"{DOMAIN} - {self.host}", + update_interval=UPDATE_INTERVAL, + ) + + @override + async def _async_update_data(self) -> dict[str, str | None]: + """Return the currently connected devices keyed by MAC address.""" + return await self.hass.async_add_executor_job(self._update) + + def _update(self) -> dict[str, str | None]: + """Query the router, re-authenticating once if the session expired.""" + if self.ubus.session_id is None: + self._login() + try: + return self._read_clients() + except PermissionError: + # The router dropped our session (e.g. after a reboot); log back in. + self._login() + try: + return self._read_clients() + except PermissionError as err: + raise UpdateFailed(f"Access denied by ubus at {self.host}") from err + + def _login(self) -> None: + """Open a ubus session, raising UpdateFailed on failure.""" + try: + session_id = self.ubus.connect() + except (ConnectionError, PermissionError, TypeError) as err: + # openwrt-ubus-rpc raises TypeError when the HTTP request itself + # fails, because it subscripts a None response. + raise UpdateFailed(f"Error connecting to ubus at {self.host}") from err + if session_id is None: + raise UpdateFailed(f"Invalid credentials for ubus at {self.host}") + + def _read_clients(self) -> dict[str, str | None]: + """Return authorized clients mapped to their DHCP hostname. + + PermissionError is left to propagate so the caller can re-authenticate. + """ + clients = self._fetch_hostapd_clients() + if self._mac2name is None: + self._mac2name = self._generate_mac2name() + return { + mac: self._name_for(mac) + for mac, client in clients.items() + if client["authorized"] + } + + def _fetch_hostapd_clients(self) -> dict[str, dict]: + """Return the raw hostapd client table merged across all interfaces.""" + try: + if not self._hostapd: + if not (hostapd := self.ubus.get_hostapd()): + raise UpdateFailed(f"No hostapd data from ubus at {self.host}") + self._hostapd = list(hostapd) + clients: dict[str, dict] = {} + for interface in self._hostapd: + if result := self.ubus.get_hostapd_clients(interface): + clients.update(result["clients"]) + except ConnectionError as err: + raise UpdateFailed(f"Error querying ubus at {self.host}") from err + return clients + + def _name_for(self, mac: str) -> str | None: + """Return the DHCP hostname for a MAC address, if known.""" + if self._mac2name is None: + return None + return self._mac2name.get(mac.upper()) + + def _generate_mac2name(self) -> dict[str, str] | None: + """Build the MAC-to-hostname map for the configured DHCP software.""" + if self.dhcp_software == "dnsmasq": + return self._dnsmasq_mac2name() + if self.dhcp_software == "odhcpd": + return self._odhcpd_mac2name() + return {} + + def _dnsmasq_mac2name(self) -> dict[str, str] | None: + """Read the dnsmasq lease file. Returns None to retry if unavailable.""" + try: + if self._leasefile is None: + if not (result := self.ubus.get_uci_config("dhcp", "dnsmasq")): + return None + self._leasefile = next(iter(result["values"].values()))["leasefile"] + result = self.ubus.file_read(self._leasefile) + except ConnectionError as err: + raise UpdateFailed( + f"Error reading leases from ubus at {self.host}" + ) from err + + if not result: + return None + + mac2name = {} + for line in result["data"].splitlines(): + hosts = line.split(" ") + mac2name[hosts[1].upper()] = hosts[3] + return mac2name + + def _odhcpd_mac2name(self) -> dict[str, str] | None: + """Read the odhcpd leases. Returns None to retry if unavailable.""" + try: + result = self.ubus.get_dhcp_method("ipv4leases") + except ConnectionError as err: + raise UpdateFailed( + f"Error reading leases from ubus at {self.host}" + ) from err + + if not result: + return None + + mac2name = {} + for device in result["device"].values(): + for lease in device["leases"]: + mac = ":".join( + lease["mac"][i : i + 2] for i in range(0, len(lease["mac"]), 2) + ) + mac2name[mac.upper()] = lease["hostname"] + return mac2name diff --git a/homeassistant/components/ubus/device_tracker.py b/homeassistant/components/ubus/device_tracker.py index 0ff83221647a..ae3ec18ed634 100644 --- a/homeassistant/components/ubus/device_tracker.py +++ b/homeassistant/components/ubus/device_tracker.py @@ -1,27 +1,25 @@ -"""Support for OpenWRT (ubus) routers.""" +"""Support for OpenWrt (ubus) routers as a device tracker.""" -import logging -import re from typing import override -from openwrt.ubus import Ubus import probatio from homeassistant.components.device_tracker import ( - DOMAIN as DEVICE_TRACKER_DOMAIN, PLATFORM_SCHEMA as DEVICE_TRACKER_PLATFORM_SCHEMA, - DeviceScanner, + AsyncSeeCallback, + ScannerEntity, ) +from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME -from homeassistant.core import HomeAssistant -from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.typing import ConfigType +from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import config_validation as cv, issue_registry as ir +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType +from homeassistant.helpers.update_coordinator import CoordinatorEntity -_LOGGER = logging.getLogger(__name__) - -CONF_DHCP_SOFTWARE = "dhcp_software" -DEFAULT_DHCP_SOFTWARE = "dnsmasq" -DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] +from .const import CONF_DHCP_SOFTWARE, DEFAULT_DHCP_SOFTWARE, DHCP_SOFTWARES, DOMAIN +from .coordinator import UbusConfigEntry, UbusDataUpdateCoordinator PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( { @@ -35,158 +33,99 @@ PLATFORM_SCHEMA = DEVICE_TRACKER_PLATFORM_SCHEMA.extend( ) -def get_scanner(hass: HomeAssistant, config: ConfigType) -> DeviceScanner | None: - """Validate the configuration and return an ubus scanner.""" - config = config[DEVICE_TRACKER_DOMAIN] +async def async_setup_scanner( + hass: HomeAssistant, + config: ConfigType, + async_see: AsyncSeeCallback, + discovery_info: DiscoveryInfoType | None = None, +) -> bool: + """Import the legacy YAML device tracker into a config entry.""" + import_data = { + CONF_HOST: config[CONF_HOST], + CONF_USERNAME: config[CONF_USERNAME], + CONF_PASSWORD: config[CONF_PASSWORD], + CONF_DHCP_SOFTWARE: config[CONF_DHCP_SOFTWARE], + } + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_IMPORT}, data=import_data + ) - dhcp_sw = config[CONF_DHCP_SOFTWARE] - scanner: DeviceScanner - if dhcp_sw == "dnsmasq": - scanner = DnsmasqUbusDeviceScanner(config) - elif dhcp_sw == "odhcpd": - scanner = OdhcpdUbusDeviceScanner(config) - else: - scanner = UbusDeviceScanner(config) + if result["type"] is FlowResultType.ABORT and result["reason"] in ( + "cannot_connect", + "invalid_auth", + ): + ir.async_create_issue( + hass, + DOMAIN, + f"yaml_import_{result['reason']}", + is_fixable=False, + issue_domain=DOMAIN, + severity=ir.IssueSeverity.ERROR, + translation_key=f"yaml_import_{result['reason']}", + translation_placeholders={"host": config[CONF_HOST]}, + ) + return False - return scanner if scanner.success_init else None + ir.async_create_issue( + hass, + HOMEASSISTANT_DOMAIN, + f"deprecated_yaml_{DOMAIN}", + breaks_in_ha_version="2027.5.0", + is_fixable=False, + issue_domain=DOMAIN, + severity=ir.IssueSeverity.WARNING, + translation_key="deprecated_yaml", + translation_placeholders={ + "domain": DOMAIN, + "integration_title": "OpenWrt (ubus)", + }, + ) + return True -def _refresh_on_access_denied(func): - """If remove rebooted, it lost our session so rebuild one and try again.""" +async def async_setup_entry( + hass: HomeAssistant, + config_entry: UbusConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the device tracker for a ubus config entry.""" + coordinator = config_entry.runtime_data + tracked: set[str] = set() - def decorator(self, *args, **kwargs): - """Wrap the function to refresh session_id on PermissionError.""" - try: - return func(self, *args, **kwargs) - except PermissionError: - _LOGGER.warning( - "Invalid session detected. Trying to refresh session_id and re-run RPC" - ) - self.ubus.connect() + @callback + def _async_add_new_devices() -> None: + new_macs = [mac for mac in coordinator.data if mac not in tracked] + tracked.update(new_macs) + if new_macs: + async_add_entities(UbusScannerEntity(coordinator, mac) for mac in new_macs) - return func(self, *args, **kwargs) - - return decorator + config_entry.async_on_unload(coordinator.async_add_listener(_async_add_new_devices)) + _async_add_new_devices() -class UbusDeviceScanner(DeviceScanner): - """Class which queries a wireless router running OpenWrt firmware. +class UbusScannerEntity(CoordinatorEntity[UbusDataUpdateCoordinator], ScannerEntity): + """Representation of a device connected to an OpenWrt router.""" - Adapted from Tomato scanner. - """ - - def __init__(self, config): - """Initialize the scanner.""" - self.host = config[CONF_HOST] - self.username = config[CONF_USERNAME] - self.password = config[CONF_PASSWORD] - - self.parse_api_pattern = re.compile(r"(?P\w*) = (?P.*);") - self.last_results = {} - self.url = f"http://{self.host}/ubus" - - self.ubus = Ubus(self.url, self.username, self.password) - self.hostapd = [] - self.mac2name = None - self.success_init = self.ubus.connect() is not None + def __init__(self, coordinator: UbusDataUpdateCoordinator, mac: str) -> None: + """Initialize the tracked device.""" + super().__init__(coordinator) + self._mac = mac + self._attr_name = coordinator.data.get(mac) or mac + @property @override - def scan_devices(self): - """Scan for new devices and return a list with found device IDs.""" - self._update_info() - return self.last_results + def mac_address(self) -> str: + """Return the MAC address of the device.""" + return self._mac - def _generate_mac2name(self): - """Return empty MAC to name dict. Overridden if DHCP server is set.""" - self.mac2name = {} - - @_refresh_on_access_denied + @property @override - def get_device_name(self, device): - """Return the name of the given device or None if we don't know.""" - if self.mac2name is None: - self._generate_mac2name() - if self.mac2name is None: - # Generation of mac2name dictionary failed - return None - return self.mac2name.get(device.upper(), None) + def is_connected(self) -> bool: + """Return whether the device is connected to the router.""" + return self._mac in self.coordinator.data + @property @override - async def async_get_extra_attributes(self, device: str) -> dict[str, str]: - """Return the host to distinguish between multiple routers.""" - return {"host": self.host} - - @_refresh_on_access_denied - def _update_info(self): - """Ensure the information from the router is up to date. - - Returns boolean if scanning successful. - """ - if not self.success_init: - return False - - _LOGGER.debug("Checking hostapd") - - if not self.hostapd: - hostapd = self.ubus.get_hostapd() - self.hostapd.extend(hostapd.keys()) - - self.last_results = [] - results = 0 - # for each access point - for hostapd in self.hostapd: - if result := self.ubus.get_hostapd_clients(hostapd): - results = results + 1 - # Check for each device is authorized (valid wpa key) - for key in result["clients"]: - device = result["clients"][key] - if device["authorized"]: - self.last_results.append(key) - - return bool(results) - - -class DnsmasqUbusDeviceScanner(UbusDeviceScanner): - """Implement the Ubus device scanning for the dnsmasq DHCP server.""" - - def __init__(self, config): - """Initialize the scanner.""" - super().__init__(config) - self.leasefile = None - - @override - def _generate_mac2name(self): - if self.leasefile is None: - if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): - values = result["values"].values() - self.leasefile = next(iter(values))["leasefile"] - else: - return - - result = self.ubus.file_read(self.leasefile) - if result: - self.mac2name = {} - for line in result["data"].splitlines(): - hosts = line.split(" ") - self.mac2name[hosts[1].upper()] = hosts[3] - else: - # Error, handled in the ubus.file_read() - return - - -class OdhcpdUbusDeviceScanner(UbusDeviceScanner): - """Implement the Ubus device scanning for the odhcp DHCP server.""" - - @override - def _generate_mac2name(self): - if result := self.ubus.get_dhcp_method("ipv4leases"): - self.mac2name = {} - for device in result["device"].values(): - for lease in device["leases"]: - mac = lease["mac"] # mac = aabbccddeeff - # Convert it to expected format with colon - mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) - self.mac2name[mac.upper()] = lease["hostname"] - else: - # Error, handled in the ubus.get_dhcp_method() - return + def hostname(self) -> str | None: + """Return the hostname of the device.""" + return self.coordinator.data.get(self._mac) diff --git a/homeassistant/components/ubus/manifest.json b/homeassistant/components/ubus/manifest.json index dcbfbfa869b0..3b8490180561 100644 --- a/homeassistant/components/ubus/manifest.json +++ b/homeassistant/components/ubus/manifest.json @@ -6,7 +6,9 @@ "computers_network.routers_network" ], "codeowners": [], + "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/ubus", + "integration_type": "hub", "iot_class": "local_polling", "loggers": ["openwrt"], "quality_scale": "legacy", diff --git a/homeassistant/components/ubus/strings.json b/homeassistant/components/ubus/strings.json new file mode 100644 index 000000000000..da86c26b4f35 --- /dev/null +++ b/homeassistant/components/ubus/strings.json @@ -0,0 +1,43 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" + }, + "error": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]" + }, + "step": { + "user": { + "data": { + "dhcp_software": "DHCP software", + "host": "[%key:common::config_flow::data::host%]", + "password": "[%key:common::config_flow::data::password%]", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "dhcp_software": "The DHCP server running on the router, used to resolve device hostnames." + } + } + } + }, + "issues": { + "yaml_import_cannot_connect": { + "description": "The YAML configuration for OpenWrt (ubus) at `{host}` could not be imported because the connection failed.\n\nPlease check that `{host}` is reachable, update your `configuration.yaml` if needed, and restart Home Assistant.", + "title": "YAML import failed: cannot connect" + }, + "yaml_import_invalid_auth": { + "description": "The YAML configuration for OpenWrt (ubus) at `{host}` could not be imported because the credentials were rejected.\n\nPlease check the username and password in your `configuration.yaml`, then restart Home Assistant.", + "title": "YAML import failed: invalid authentication" + } + }, + "selector": { + "dhcp_software": { + "options": { + "dnsmasq": "dnsmasq", + "none": "None", + "odhcpd": "odhcpd" + } + } + } +} diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 0988cdc58255..140c98229887 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -873,6 +873,7 @@ FLOWS = { "twilio", "twinkly", "twitch", + "ubus", "uhoo", "ukraine_alarm", "unifi", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 13424e61b1cc..27ab6ad2b05f 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -8270,7 +8270,7 @@ }, "ubus": { "integration_type": "hub", - "config_flow": false, + "config_flow": true, "iot_class": "local_polling", "categories": [ "presence_location.network_presence", diff --git a/tests/components/ubus/__init__.py b/tests/components/ubus/__init__.py new file mode 100644 index 000000000000..b0b51d14749a --- /dev/null +++ b/tests/components/ubus/__init__.py @@ -0,0 +1 @@ +"""Tests for the OpenWrt (ubus) integration.""" diff --git a/tests/components/ubus/conftest.py b/tests/components/ubus/conftest.py new file mode 100644 index 000000000000..d65e35122faa --- /dev/null +++ b/tests/components/ubus/conftest.py @@ -0,0 +1,97 @@ +"""Fixtures for the OpenWrt (ubus) integration tests.""" + +from collections.abc import Generator +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.ubus.const import ( + CONF_DHCP_SOFTWARE, + DEFAULT_DHCP_SOFTWARE, + DOMAIN, +) +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME + +MOCK_HOST = "192.168.1.1" + +MOCK_CONFIG = { + CONF_HOST: MOCK_HOST, + CONF_USERNAME: "root", + CONF_PASSWORD: "password", + CONF_DHCP_SOFTWARE: DEFAULT_DHCP_SOFTWARE, +} + +MAC_PHONE = "AA:BB:CC:DD:EE:FF" +MAC_LAPTOP = "11:22:33:44:55:66" +MAC_GUEST = "99:88:77:66:55:44" + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Override async_setup_entry.""" + with patch( + "homeassistant.components.ubus.async_setup_entry", return_value=None + ) as mock_setup_entry: + yield mock_setup_entry + + +@pytest.fixture +def dhcp_software() -> str: + """Return the DHCP software the mock config entry is created with.""" + return DEFAULT_DHCP_SOFTWARE + + +@pytest.fixture +def mock_config_entry(dhcp_software: str) -> MockConfigEntry: + """Return a mock config entry.""" + return MockConfigEntry( + domain=DOMAIN, + data={**MOCK_CONFIG, CONF_DHCP_SOFTWARE: dhcp_software}, + title=MOCK_HOST, + ) + + +@pytest.fixture +def mock_ubus() -> Generator[MagicMock]: + """Mock the Ubus client with the raw router API responses.""" + with ( + patch("homeassistant.components.ubus.coordinator.Ubus", autospec=True) as mock, + patch("homeassistant.components.ubus.config_flow.Ubus", new=mock), + ): + instance = mock.return_value + instance.session_id = None + + def _connect() -> str: + instance.session_id = "session-id" + return "session-id" + + instance.connect.side_effect = _connect + instance.get_hostapd.return_value = {"hostapd.wlan0": {}} + instance.get_hostapd_clients.return_value = { + "clients": { + MAC_PHONE: {"authorized": True}, + MAC_LAPTOP: {"authorized": True}, + MAC_GUEST: {"authorized": False}, + } + } + instance.get_uci_config.return_value = { + "values": {"cfg01": {"leasefile": "/var/dhcp/dnsmasq.leases"}} + } + instance.file_read.return_value = { + "data": ( + "1600000000 aa:bb:cc:dd:ee:ff 192.168.1.10 my-phone *\n" + "1600000000 11:22:33:44:55:66 192.168.1.11 my-laptop *" + ) + } + instance.get_dhcp_method.return_value = { + "device": { + "br-lan": { + "leases": [ + {"mac": "aabbccddeeff", "hostname": "my-phone"}, + {"mac": "112233445566", "hostname": "my-laptop"}, + ] + } + } + } + yield mock diff --git a/tests/components/ubus/test_config_flow.py b/tests/components/ubus/test_config_flow.py new file mode 100644 index 000000000000..08d8e3ad2e30 --- /dev/null +++ b/tests/components/ubus/test_config_flow.py @@ -0,0 +1,190 @@ +"""Tests for the OpenWrt (ubus) config flow.""" + +from unittest.mock import AsyncMock, MagicMock + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.ubus.const import CONF_DHCP_SOFTWARE, DOMAIN +from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from .conftest import MOCK_CONFIG, MOCK_HOST + +USER_INPUT = { + CONF_HOST: MOCK_HOST, + CONF_USERNAME: "root", + CONF_PASSWORD: "password", +} + + +async def test_user_flow_success( + hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_ubus: MagicMock +) -> None: + """Test the user flow creates an entry with the default DHCP software.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == MOCK_HOST + assert result["data"] == MOCK_CONFIG + + +async def test_user_flow_cannot_connect( + hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_ubus: MagicMock +) -> None: + """Test the user flow recovers after a connection error.""" + mock_ubus.return_value.connect.side_effect = ConnectionError("boom") + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_connect"} + + mock_ubus.return_value.connect.side_effect = None + mock_ubus.return_value.connect.return_value = "session-id" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +@pytest.mark.parametrize( + "connect", + [ + pytest.param( + {"side_effect": PermissionError("Access denied")}, id="access_denied" + ), + pytest.param({"side_effect": None, "return_value": None}, id="no_session"), + ], +) +async def test_user_flow_invalid_auth( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_ubus: MagicMock, + connect: dict, +) -> None: + """Test the user flow reports invalid credentials and then recovers.""" + mock_ubus.return_value.connect.configure_mock(**connect) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "invalid_auth"} + + mock_ubus.return_value.connect.configure_mock( + side_effect=None, return_value="session-id" + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_flow_already_configured( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_ubus: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the user flow aborts when the host is already configured.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=USER_INPUT + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_import_flow( + hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_ubus: MagicMock +) -> None: + """Test importing a YAML configuration.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_CONFIG + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == MOCK_HOST + assert result["data"] == MOCK_CONFIG + + +async def test_import_flow_already_configured( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_ubus: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the import flow aborts when the host is already configured.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_CONFIG + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_import_flow_preserves_dhcp_software( + hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_ubus: MagicMock +) -> None: + """Test a non-default DHCP software choice survives the import.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_IMPORT}, + data={**MOCK_CONFIG, CONF_DHCP_SOFTWARE: "odhcpd"}, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_DHCP_SOFTWARE] == "odhcpd" + + +@pytest.mark.parametrize( + ("side_effect", "reason"), + [ + pytest.param(TypeError, "cannot_connect", id="cannot_connect"), + pytest.param(PermissionError, "invalid_auth", id="invalid_auth"), + ], +) +async def test_import_flow_errors( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_ubus: MagicMock, + side_effect: type[Exception], + reason: str, +) -> None: + """Test the import flow aborts when the router can't be logged in to.""" + mock_ubus.return_value.connect.side_effect = side_effect + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_CONFIG + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason diff --git a/tests/components/ubus/test_device_tracker.py b/tests/components/ubus/test_device_tracker.py new file mode 100644 index 000000000000..5be416117e61 --- /dev/null +++ b/tests/components/ubus/test_device_tracker.py @@ -0,0 +1,101 @@ +"""Tests for the OpenWrt (ubus) device tracker.""" + +from unittest.mock import MagicMock + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.ubus.const import DOMAIN +from homeassistant.config_entries import SOURCE_IMPORT +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er, issue_registry as ir +from homeassistant.setup import async_setup_component + +from .conftest import MAC_GUEST, MAC_LAPTOP, MAC_PHONE, MOCK_CONFIG, MOCK_HOST + + +@pytest.mark.parametrize( + ("dhcp_software", "expected_names"), + [ + pytest.param("dnsmasq", {"my-phone", "my-laptop"}, id="dnsmasq"), + pytest.param("odhcpd", {"my-phone", "my-laptop"}, id="odhcpd"), + pytest.param("none", {MAC_PHONE, MAC_LAPTOP}, id="none"), + ], +) +async def test_only_authorized_clients_are_tracked( + hass: HomeAssistant, + mock_ubus: MagicMock, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, + expected_names: set[str], +) -> None: + """Test that authorized clients become entities and names resolve per backend.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entries = er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) + + assert {e.unique_id for e in entries} == {MAC_PHONE, MAC_LAPTOP} + assert MAC_GUEST not in {e.unique_id for e in entries} + assert {e.original_name for e in entries} == expected_names + + +async def test_setup_scanner_imports_yaml( + hass: HomeAssistant, mock_ubus: MagicMock +) -> None: + """Test the legacy YAML platform imports itself into a config entry.""" + assert await async_setup_component( + hass, + "device_tracker", + { + "device_tracker": [ + { + "platform": DOMAIN, + CONF_HOST: MOCK_HOST, + CONF_USERNAME: "root", + CONF_PASSWORD: "password", + } + ] + }, + ) + await hass.async_block_till_done() + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + assert entries[0].source == SOURCE_IMPORT + assert entries[0].data == MOCK_CONFIG + + +async def test_setup_scanner_creates_issue_on_cannot_connect( + hass: HomeAssistant, + mock_ubus: MagicMock, + issue_registry: ir.IssueRegistry, +) -> None: + """Test a repair issue is raised when the YAML import cannot connect.""" + mock_ubus.return_value.connect.side_effect = TypeError + + assert await async_setup_component( + hass, + "device_tracker", + { + "device_tracker": [ + { + "platform": DOMAIN, + CONF_HOST: MOCK_HOST, + CONF_USERNAME: "root", + CONF_PASSWORD: "password", + } + ] + }, + ) + await hass.async_block_till_done() + + assert not hass.config_entries.async_entries(DOMAIN) + issue = issue_registry.async_get_issue(DOMAIN, "yaml_import_cannot_connect") + assert issue is not None + assert issue.translation_placeholders == {"host": MOCK_HOST} diff --git a/tests/components/ubus/test_init.py b/tests/components/ubus/test_init.py new file mode 100644 index 000000000000..15182c1cc8bd --- /dev/null +++ b/tests/components/ubus/test_init.py @@ -0,0 +1,88 @@ +"""Tests for the OpenWrt (ubus) integration setup.""" + +from typing import Any +from unittest.mock import MagicMock + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import MAC_LAPTOP, MAC_PHONE + + +@pytest.mark.parametrize( + ("method", "behavior"), + [ + pytest.param("connect", {"side_effect": TypeError}, id="unreachable"), + pytest.param("connect", {"side_effect": PermissionError}, id="access_denied"), + pytest.param( + "connect", {"side_effect": None, "return_value": None}, id="no_session" + ), + pytest.param( + "get_hostapd_clients", + {"side_effect": PermissionError}, + id="session_stays_denied", + ), + ], +) +async def test_setup_retry( + hass: HomeAssistant, + mock_ubus: MagicMock, + mock_config_entry: MockConfigEntry, + method: str, + behavior: dict[str, Any], +) -> None: + """Test the config entry retries setup when the router can't be read.""" + getattr(mock_ubus.return_value, method).configure_mock(**behavior) + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_session_refreshed_after_permission_error( + hass: HomeAssistant, + mock_ubus: MagicMock, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, +) -> None: + """Test a dropped session is re-authenticated and the scan retried.""" + mock_ubus.return_value.get_hostapd_clients.side_effect = [ + PermissionError, + { + "clients": { + MAC_PHONE: {"authorized": True}, + MAC_LAPTOP: {"authorized": True}, + } + }, + ] + + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_ubus.return_value.connect.call_count == 2 + entries = er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) + assert {e.unique_id for e in entries} == {MAC_PHONE, MAC_LAPTOP} + + +async def test_unload_entry( + hass: HomeAssistant, mock_ubus: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Test the config entry unloads cleanly.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.LOADED + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED