diff --git a/homeassistant/components/evohome/manifest.json b/homeassistant/components/evohome/manifest.json index cec557c3a502..75d70a209284 100644 --- a/homeassistant/components/evohome/manifest.json +++ b/homeassistant/components/evohome/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["evohomeasync", "evohomeasync2"], "quality_scale": "legacy", - "requirements": ["evohome-async==3.2.2"] + "requirements": ["evohome-async==3.3.0"] } diff --git a/homeassistant/components/evohome/storage.py b/homeassistant/components/evohome/storage.py index f4394f06fba8..ea83dc6d18d0 100644 --- a/homeassistant/components/evohome/storage.py +++ b/homeassistant/components/evohome/storage.py @@ -1,5 +1,6 @@ """Support for (EMEA/EU-based) Honeywell TCC systems.""" +from collections.abc import Mapping from datetime import timedelta from typing import Any, NotRequired, TypedDict, override @@ -8,7 +9,9 @@ from evohomeasync.auth import ( SZ_SESSION_ID_EXPIRES, AbstractSessionManager, ) -from evohomeasync2.auth import AbstractTokenManager +from evohomeasync.schemas import TccFailureCode +from evohomeasync2.auth import CREDS_USER_PASSWORD, AbstractTokenManager +from evohomeasync2.schemas.const import OAUTH_GRANT_TYPE, TccOAuthError from homeassistant.core import HomeAssistant from homeassistant.helpers.storage import Store @@ -41,6 +44,20 @@ class TokenManager(AbstractTokenManager, AbstractSessionManager): self._store: Store[_TokenStoreT] = Store(hass, STORAGE_VER, STORAGE_KEY) self._store_initialized = False # True once cache loaded first time + @override + def _is_bad_credentials(self, data: Mapping[str, str], code: str | None) -> bool: + """Return True if a failed request (v1 or v2) was refused for the credentials. + + Without this, only the v2 check would apply (it is first in the MRO). + """ + + if ( + code == TccOAuthError.INVALID_GRANT + and data.get(OAUTH_GRANT_TYPE) == CREDS_USER_PASSWORD[OAUTH_GRANT_TYPE] + ): + return True + return code == TccFailureCode.EMAIL_OR_PASSWORD_INCORRECT + @override async def get_access_token(self) -> str: """Return a valid access token. diff --git a/requirements_all.txt b/requirements_all.txt index 8f1b7098f6cb..e17c4d628705 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1038,7 +1038,7 @@ eurotronic-cometblue-ha==2.0.0 # evdev==1.9.3 # homeassistant.components.evohome -evohome-async==3.2.2 +evohome-async==3.3.0 # homeassistant.components.bryant_evolution evolutionhttp==0.0.19 diff --git a/tests/components/evohome/test_init.py b/tests/components/evohome/test_init.py index 4421f9886713..3136859c5d62 100644 --- a/tests/components/evohome/test_init.py +++ b/tests/components/evohome/test_init.py @@ -2,20 +2,19 @@ from http import HTTPStatus import logging -from unittest.mock import Mock, patch +from unittest.mock import AsyncMock, Mock, patch import aiohttp -from evohomeasync2 import exceptions as evo_exc import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components.evohome.const import DOMAIN +from homeassistant.components.evohome.const import DOMAIN, EVOHOME_DATA from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from homeassistant.setup import async_setup_component -from .conftest import mock_post_request, setup_evohome +from .conftest import mock_make_request, mock_post_request, setup_evohome from .const import USERNAME _MSG_429 = ( @@ -44,7 +43,7 @@ LOG_FAIL_CREDENTIALS = ( "homeassistant.components.evohome", logging.ERROR, "Failed to fetch initial data: " - "Authenticator response is invalid: {'error': 'invalid_grant'}", + 'Authenticator response is invalid: 400 Bad Request, response={"error": "invalid_grant"}', ) LOG_FAIL_GATEWAY = ( "homeassistant.components.evohome", @@ -91,9 +90,28 @@ LOG_SETUP_FAILED = ( EXC_BAD_CONNECTION = aiohttp.ClientConnectionError( "Connection error", ) -EXC_BAD_CREDENTIALS = evo_exc.AuthenticationFailedError( - "Authenticator response is invalid: {'error': 'invalid_grant'}", - status=HTTPStatus.BAD_REQUEST, + + +def _mock_response(status: HTTPStatus, body: dict | list) -> Mock: + """Return a mock of a response from the vendor's server (JSON, a HTTP error).""" + rsp = Mock(spec=aiohttp.ClientResponse, status=status, headers={}) + rsp.content_type = "application/json" + rsp.json = AsyncMock(return_value=body) + rsp.raise_for_status.side_effect = aiohttp.ClientResponseError( + Mock(), (), status=status, message=status.phrase + ) + return rsp + + +# the vendor's response to a bad username/password is not an exception (v2, then v1) +RSP_BAD_CREDENTIALS = Mock( + return_value=_mock_response(HTTPStatus.BAD_REQUEST, {"error": "invalid_grant"}) +) +RSP_BAD_CREDENTIALS_V1 = Mock( + return_value=_mock_response( + HTTPStatus.UNAUTHORIZED, + [{"code": "EmailOrPasswordIncorrect", "message": "..."}], + ) ) EXC_TOO_MANY_REQUESTS = aiohttp.ClientResponseError( Mock(), @@ -105,9 +123,9 @@ EXC_BAD_GATEWAY = aiohttp.ClientResponseError( Mock(), (), status=HTTPStatus.BAD_GATEWAY, message=HTTPStatus.BAD_GATEWAY.phrase ) -AUTHENTICATION_TESTS: dict[Exception, list] = { +AUTHENTICATION_TESTS: dict[Exception | Mock, list] = { EXC_BAD_CONNECTION: [LOG_HINT_OTH_AUTH, LOG_FAIL_CONNECTION, LOG_SETUP_FAILED], - EXC_BAD_CREDENTIALS: [LOG_HINT_USR_AUTH, LOG_FAIL_CREDENTIALS, LOG_SETUP_FAILED], + RSP_BAD_CREDENTIALS: [LOG_HINT_USR_AUTH, LOG_FAIL_CREDENTIALS, LOG_SETUP_FAILED], EXC_BAD_GATEWAY: [LOG_HINT_OTH_AUTH, LOG_FAIL_GATEWAY, LOG_SETUP_FAILED], EXC_TOO_MANY_REQUESTS: [LOG_HINT_429_AUTH, LOG_FAIL_TOO_MANY, LOG_SETUP_FAILED], } @@ -123,7 +141,7 @@ CLIENT_REQUEST_TESTS: dict[Exception, list] = { async def test_authentication_failure_v2( hass: HomeAssistant, config: dict[str, str], - exception: Exception, + exception: Exception | Mock, caplog: pytest.LogCaptureFixture, ) -> None: """Test failure to setup an evohome-compatible system. @@ -145,6 +163,31 @@ async def test_authentication_failure_v2( assert caplog.record_tuples == AUTHENTICATION_TESTS[exception] +async def test_bad_credentials_v1( + hass: HomeAssistant, + config: dict[str, str], + caplog: pytest.LogCaptureFixture, +) -> None: + """Test high-precision temps are disabled if the v1 API refuses the credentials.""" + + with ( + patch( + "evohomeasync2.auth.AbstractTokenManager._post_access_token_request", + mock_post_request("default"), + ), + patch( + "_evohome.credentials.CredentialsManagerBase._request", + side_effect=RSP_BAD_CREDENTIALS_V1, + ), + patch("_evohome.auth.AbstractAuth._make_request", mock_make_request("default")), + ): + assert await async_setup_component(hass, DOMAIN, {DOMAIN: config}) + await hass.async_block_till_done() + + assert hass.data[EVOHOME_DATA].coordinator.client_v1 is None + assert "The feature will be disabled until next restart" in caplog.text + + @pytest.mark.parametrize("exception", CLIENT_REQUEST_TESTS) async def test_client_request_failure_v2( hass: HomeAssistant,