From 8aaa7dc9fcc2c44c6817145bb00b371ac8068446 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:38:59 +0200 Subject: [PATCH] Handle UniFi MFA accounts, login rate limits and site request errors (#187782) --- homeassistant/components/unifi/config_flow.py | 38 ++++- homeassistant/components/unifi/errors.py | 4 + homeassistant/components/unifi/hub/api.py | 12 +- homeassistant/components/unifi/strings.json | 1 + tests/components/unifi/test_config_flow.py | 151 +++++++++++++++++- tests/components/unifi/test_hub.py | 25 ++- 6 files changed, 219 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/unifi/config_flow.py b/homeassistant/components/unifi/config_flow.py index 71faa16aa0fe..083d92dab19a 100644 --- a/homeassistant/components/unifi/config_flow.py +++ b/homeassistant/components/unifi/config_flow.py @@ -6,13 +6,16 @@ Reauthentication when issue with credentials are reported. Configuration of options through options flow. """ +import asyncio from collections.abc import Iterator, Mapping from contextlib import contextmanager +import json import operator import socket from types import MappingProxyType from typing import Any, override +import aiounifi from aiounifi.interfaces.sites import Sites import probatio @@ -55,14 +58,16 @@ from .const import ( CONF_TRACK_WIRED_CLIENTS, DEFAULT_DPI_RESTRICTIONS, DOMAIN, + LOGGER, ) -from .errors import AuthenticationRequired, CannotConnect +from .errors import AuthenticationRequired, CannotConnect, MfaRequired from .hub import UnifiHub, get_unifi_api DEFAULT_HOST = "unifi" DEFAULT_PORT = 443 DEFAULT_SITE_ID = "default" DEFAULT_VERIFY_SSL = False +SITE_REQUEST_TIMEOUT = 10 class UnifiFlowHandler(ConfigFlow, domain=DOMAIN): @@ -277,7 +282,34 @@ class UnifiFlowHandler(ConfigFlow, domain=DOMAIN): async def _async_update_sites(self, data: Mapping[str, Any]) -> Sites: """Get updated sites through UniFi API.""" hub = await get_unifi_api(self.hass, MappingProxyType(data)) - await hub.sites.update() + try: + async with asyncio.timeout(SITE_REQUEST_TIMEOUT): + await hub.sites.update() + except ( + aiounifi.Forbidden, + aiounifi.LoginRequired, + aiounifi.NoPermission, + aiounifi.Unauthorized, + ) as err: + LOGGER.warning( + "UniFi Network at %s rejected the site request: %s", + data[CONF_HOST], + type(err).__name__, + ) + raise AuthenticationRequired from err + # aiounifi 97 does not wrap JSON decode errors, newer releases do + except (TimeoutError, json.JSONDecodeError, aiounifi.AiounifiException) as err: + LOGGER.warning( + "Error fetching sites from UniFi Network at %s: %r", + data[CONF_HOST], + err, + ) + raise CannotConnect from err + if not hub.sites.values(): + # aiounifi 97 returns no sites when the console answers with HTML, + # as it does while the Network application is missing or starting + LOGGER.warning("No sites found on UniFi Network at %s", data[CONF_HOST]) + raise CannotConnect return hub.sites @callback @@ -454,6 +486,8 @@ def _catch_unifi_api_flow_errors(errors: dict[str, str]) -> Iterator[None]: """Map UniFi API exceptions to config flow form errors.""" try: yield + except MfaRequired: + errors["base"] = "mfa_required" except AuthenticationRequired: errors["base"] = "faulty_credentials" except CannotConnect: diff --git a/homeassistant/components/unifi/errors.py b/homeassistant/components/unifi/errors.py index d33e862cafd4..2874237e2965 100644 --- a/homeassistant/components/unifi/errors.py +++ b/homeassistant/components/unifi/errors.py @@ -15,6 +15,10 @@ class AuthenticationRequired(UnifiException): """Unknown error occurred.""" +class MfaRequired(AuthenticationRequired): + """Account requires multi-factor authentication, which is not supported.""" + + class CannotConnect(UnifiException): """Unable to connect to UniFi Network.""" diff --git a/homeassistant/components/unifi/hub/api.py b/homeassistant/components/unifi/hub/api.py index 37ede4ab6c5a..cbb4f9bd9eac 100644 --- a/homeassistant/components/unifi/hub/api.py +++ b/homeassistant/components/unifi/hub/api.py @@ -20,7 +20,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client from ..const import CONF_SITE_ID, LOGGER -from ..errors import AuthenticationRequired, CannotConnect +from ..errors import AuthenticationRequired, CannotConnect, MfaRequired async def get_unifi_api( @@ -55,6 +55,15 @@ async def get_unifi_api( async with asyncio.timeout(10): await api.login() + except aiounifi.TwoFaTokenRequired as err: + LOGGER.warning( + "UniFi Network at %s requires multi-factor authentication, which is" + " not supported. Use a local account without multi-factor" + " authentication", + config[CONF_HOST], + ) + raise MfaRequired from err + except aiounifi.Unauthorized as err: LOGGER.warning( "Connected to UniFi Network at %s but not registered: %s", @@ -65,6 +74,7 @@ async def get_unifi_api( except ( TimeoutError, + aiounifi.AuthenticationRateLimitError, aiounifi.BadGateway, aiounifi.Forbidden, aiounifi.ServiceUnavailable, diff --git a/homeassistant/components/unifi/strings.json b/homeassistant/components/unifi/strings.json index 320f62d658d4..66f712b2482c 100644 --- a/homeassistant/components/unifi/strings.json +++ b/homeassistant/components/unifi/strings.json @@ -8,6 +8,7 @@ }, "error": { "faulty_credentials": "[%key:common::config_flow::error::invalid_auth%]", + "mfa_required": "This account requires multi-factor authentication, which is not supported. Use a local account without multi-factor authentication.", "service_unavailable": "[%key:common::config_flow::error::cannot_connect%]", "unknown_client_mac": "No client available on that MAC address" }, diff --git a/tests/components/unifi/test_config_flow.py b/tests/components/unifi/test_config_flow.py index 984f46deecac..96d640102601 100644 --- a/tests/components/unifi/test_config_flow.py +++ b/tests/components/unifi/test_config_flow.py @@ -1,10 +1,13 @@ """Test UniFi Network config flow.""" +import asyncio from collections.abc import Callable +import json import socket from typing import Any from unittest.mock import patch +import aiounifi import pytest from pytest_homeassistant.common import MockConfigEntry @@ -27,7 +30,11 @@ from homeassistant.components.unifi.const import ( CONF_TRACK_WIRED_CLIENTS, DOMAIN, ) -from homeassistant.components.unifi.errors import AuthenticationRequired, CannotConnect +from homeassistant.components.unifi.errors import ( + AuthenticationRequired, + CannotConnect, + MfaRequired, +) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, @@ -216,16 +223,79 @@ async def test_flow_raise_already_configured(hass: HomeAssistant) -> None: assert result["reason"] == "already_configured" +GET_UNIFI_API = "homeassistant.components.unifi.config_flow.get_unifi_api" +SITES_UPDATE = "aiounifi.interfaces.sites.Sites.update" + + @pytest.mark.parametrize( - ("side_effect", "error"), + ("target", "side_effect", "error"), [ - (AuthenticationRequired, "faulty_credentials"), - (CannotConnect, "service_unavailable"), + pytest.param( + GET_UNIFI_API, AuthenticationRequired, "faulty_credentials", id="auth" + ), + pytest.param(GET_UNIFI_API, MfaRequired, "mfa_required", id="mfa"), + pytest.param( + GET_UNIFI_API, CannotConnect, "service_unavailable", id="cannot_connect" + ), + pytest.param( + SITES_UPDATE, + aiounifi.RequestError, + "service_unavailable", + id="sites_request_error", + ), + pytest.param( + SITES_UPDATE, + aiounifi.ResponseError, + "service_unavailable", + id="sites_response_error", + ), + pytest.param( + SITES_UPDATE, TimeoutError, "service_unavailable", id="sites_timeout" + ), + # Without a side effect the patched update leaves the site list empty + pytest.param(SITES_UPDATE, None, "service_unavailable", id="sites_empty"), + pytest.param( + SITES_UPDATE, + json.JSONDecodeError("", "", 0), + "service_unavailable", + id="sites_invalid_json", + ), + pytest.param( + SITES_UPDATE, + aiounifi.AiounifiException, + "service_unavailable", + id="sites_unknown_error", + ), + pytest.param( + SITES_UPDATE, + aiounifi.Forbidden, + "faulty_credentials", + id="sites_forbidden", + ), + pytest.param( + SITES_UPDATE, + aiounifi.LoginRequired, + "faulty_credentials", + id="sites_login_required", + ), + pytest.param( + SITES_UPDATE, + aiounifi.NoPermission, + "faulty_credentials", + id="sites_no_permission", + ), + pytest.param( + SITES_UPDATE, + aiounifi.Unauthorized, + "faulty_credentials", + id="sites_unauthorized", + ), ], ) @pytest.mark.usefixtures("mock_default_requests") async def test_flow_fails_and_recovers( hass: HomeAssistant, + target: str, side_effect: type[Exception], error: str, ) -> None: @@ -237,10 +307,7 @@ async def test_flow_fails_and_recovers( assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" - with patch( - "homeassistant.components.unifi.config_flow.get_unifi_api", - side_effect=side_effect, - ): + with patch(target, side_effect=side_effect): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={ @@ -386,6 +453,74 @@ async def test_reconfigure_flow_update_configuration( assert config_entry.data[CONF_PASSWORD] == "new_pass" +@pytest.mark.usefixtures("mock_default_requests") +async def test_flow_site_request_timeout(hass: HomeAssistant) -> None: + """Test config flow gives up on a site request that does not answer.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + user_input = { + CONF_HOST: "1.2.3.4", + CONF_USERNAME: "username", + CONF_PASSWORD: "password", + CONF_PORT: 1234, + CONF_VERIFY_SSL: True, + } + + async def hang() -> None: + await asyncio.Event().wait() + + with ( + patch("homeassistant.components.unifi.config_flow.SITE_REQUEST_TIMEOUT", 0), + patch(SITES_UPDATE, side_effect=hang), + ): + # Fail instead of hanging if the flow does not time out + async with asyncio.timeout(1): + 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": "service_unavailable"} + + 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_reconfigure_flow_with_no_sites( + hass: HomeAssistant, config_entry_setup: MockConfigEntry +) -> None: + """Verify an empty site list is an error that can be retried, not an abort.""" + result = await config_entry_setup.start_reconfigure_flow(hass) + user_input = { + CONF_HOST: "1.2.3.4", + CONF_USERNAME: "new_name", + CONF_PASSWORD: "new_pass", + CONF_PORT: 1234, + CONF_VERIFY_SSL: True, + } + + # Without a side effect the patched update leaves the site list empty + with patch(SITES_UPDATE): + 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": "service_unavailable"} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=user_input + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + + @pytest.mark.parametrize( ("side_effect", "error"), [ diff --git a/tests/components/unifi/test_hub.py b/tests/components/unifi/test_hub.py index de9bb0bf6cf5..35a15a64d3f3 100644 --- a/tests/components/unifi/test_hub.py +++ b/tests/components/unifi/test_hub.py @@ -1,6 +1,7 @@ """Test UniFi Network.""" from http import HTTPStatus +import logging from types import MappingProxyType from typing import Any from unittest.mock import patch @@ -16,7 +17,11 @@ from pytest_homeassistant.test_util.aiohttp import AiohttpClientMocker from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.unifi.const import CONF_BLOCK_CLIENT, DOMAIN from homeassistant.components.unifi.coordinator import IDLE_POLL_INTERVAL, POLL_INTERVAL -from homeassistant.components.unifi.errors import AuthenticationRequired, CannotConnect +from homeassistant.components.unifi.errors import ( + AuthenticationRequired, + CannotConnect, + MfaRequired, +) from homeassistant.components.unifi.hub import get_unifi_api from homeassistant.config_entries import ConfigEntryState from homeassistant.const import CONF_HOST, EVENT_STATE_REPORTED, Platform @@ -608,6 +613,7 @@ async def test_reconnect_mechanism_exceptions( (aiounifi.ServiceUnavailable, CannotConnect), (aiounifi.RequestError, CannotConnect), (aiounifi.ResponseError, CannotConnect), + (aiounifi.AuthenticationRateLimitError, CannotConnect), (aiounifi.Unauthorized, AuthenticationRequired), (aiounifi.LoginRequired, AuthenticationRequired), (aiounifi.AiounifiException, AuthenticationRequired), @@ -625,3 +631,20 @@ async def test_get_unifi_api_fails_to_connect( pytest.raises(raised_exception), ): await get_unifi_api(hass, config_entry_data) + + +async def test_get_unifi_api_mfa_required( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + config_entry_data: MappingProxyType[str, Any], +) -> None: + """Check that a login requiring MFA is reported as such without a traceback.""" + with ( + patch("aiounifi.Controller.login", side_effect=aiounifi.TwoFaTokenRequired), + pytest.raises(MfaRequired), + ): + await get_unifi_api(hass, config_entry_data) + (record,) = [r for r in caplog.records if r.name.startswith("homeassistant")] + assert record.levelno == logging.WARNING + assert record.exc_info is None + assert "requires multi-factor authentication" in record.getMessage()