From 66b142a4ea2d7427d8d26c59fb9065ef1e6197bc Mon Sep 17 00:00:00 2001 From: G Johansson Date: Tue, 24 Nov 2026 17:53:56 +0100 Subject: [PATCH] Add reauthentication flow to Elvia (#194018) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/elvia/__init__.py | 13 +- homeassistant/components/elvia/config_flow.py | 63 +++++++- homeassistant/components/elvia/importer.py | 4 + homeassistant/components/elvia/strings.json | 16 +- tests/components/elvia/test_config_flow.py | 144 ++++++++++++++++++ tests/components/elvia/test_init.py | 87 ++++++++++- 6 files changed, 316 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/elvia/__init__.py b/homeassistant/components/elvia/__init__.py index 664d6dff4f07..67bfc6145dcd 100644 --- a/homeassistant/components/elvia/__init__.py +++ b/homeassistant/components/elvia/__init__.py @@ -7,7 +7,7 @@ from elvia import error as ElviaError from homeassistant.const import CONF_API_TOKEN from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryError +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryError from homeassistant.helpers.event import async_track_time_interval from .const import CONF_METERING_POINT_ID, DOMAIN, LOGGER @@ -29,11 +29,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: """Import meter values.""" try: await importer.import_meter_values() + except ElviaError.AuthError: + entry.async_start_reauth(hass) except ElviaError.ElviaException as exception: LOGGER.exception("Unknown error %s", exception) try: await importer.import_meter_values() + except ElviaError.AuthError as exception: + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key="invalid_auth", + ) from exception except ElviaError.ElviaException as exception: raise ConfigEntryError( translation_domain=DOMAIN, @@ -47,3 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: timedelta(minutes=60), ) ) + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Unload a config entry.""" diff --git a/homeassistant/components/elvia/config_flow.py b/homeassistant/components/elvia/config_flow.py index 108f78883ef9..fcbea1f96fdc 100644 --- a/homeassistant/components/elvia/config_flow.py +++ b/homeassistant/components/elvia/config_flow.py @@ -1,5 +1,6 @@ """Config flow for Elvia integration.""" +from collections.abc import Mapping from datetime import timedelta from typing import TYPE_CHECKING, Any, override @@ -12,6 +13,9 @@ from homeassistant.util import dt as dt_util from .const import CONF_METERING_POINT_ID, DOMAIN, LOGGER +if TYPE_CHECKING: + from elvia.types.meter_value_types import MeterValueResponse + class ElviaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Elvia.""" @@ -30,14 +34,8 @@ class ElviaConfigFlow(ConfigFlow, domain=DOMAIN): errors: dict[str, str] = {} if user_input is not None: self._api_token = api_token = user_input[CONF_API_TOKEN] - client = Elvia(meter_value_token=api_token).meter_value() try: - end_time = dt_util.utcnow() - results = await client.get_meter_values( - start_time=(end_time - timedelta(hours=1)).isoformat(), - end_time=end_time.isoformat(), - ) - + results = await _async_get_meter_values(api_token) except ElviaError.AuthError as exception: LOGGER.error("Authentication error %s", exception) errors["base"] = "invalid_auth" @@ -72,6 +70,47 @@ class ElviaConfigFlow(ConfigFlow, domain=DOMAIN): errors=errors, ) + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle reauthentication on an authentication error.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Ask for a new API token.""" + errors: dict[str, str] = {} + if user_input is not None: + reauth_entry = self._get_reauth_entry() + api_token = user_input[CONF_API_TOKEN] + try: + results = await _async_get_meter_values(api_token) + except ElviaError.AuthError: + errors["base"] = "invalid_auth" + except ElviaError.ElviaException as exception: + LOGGER.error("Unknown error %s", exception) + errors["base"] = "unknown" + else: + metering_point_ids = [ + x["meteringPointId"] for x in results.get("meteringpoints", []) + ] + if reauth_entry.unique_id not in metering_point_ids: + return self.async_abort(reason="wrong_account") + return self.async_update_reload_and_abort( + reauth_entry, data_updates={CONF_API_TOKEN: api_token} + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=probatio.Schema( + { + probatio.Required(probatio.Secret(CONF_API_TOKEN)): str, + } + ), + errors=errors, + ) + async def async_step_select_meter( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -116,3 +155,13 @@ class ElviaConfigFlow(ConfigFlow, domain=DOMAIN): CONF_METERING_POINT_ID: metering_point_id, }, ) + + +async def _async_get_meter_values(api_token: str) -> MeterValueResponse: + """Get the meter values of the last hour for all metering points of the token.""" + client = Elvia(meter_value_token=api_token).meter_value() + end_time = dt_util.utcnow() + return await client.get_meter_values( + start_time=(end_time - timedelta(hours=1)).isoformat(), + end_time=end_time.isoformat(), + ) diff --git a/homeassistant/components/elvia/importer.py b/homeassistant/components/elvia/importer.py index 979f84fabb7b..a75c0a1d9027 100644 --- a/homeassistant/components/elvia/importer.py +++ b/homeassistant/components/elvia/importer.py @@ -81,6 +81,8 @@ class ElviaImporter: since=until - timedelta(days=365 * year), until=until - timedelta(days=365 * (year - 1)), ) + except ElviaError.AuthError: + raise except ElviaError.ElviaException: # This will raise if the contract have no data for the # year, we can safely ignore this @@ -100,6 +102,8 @@ class ElviaImporter: ), until=dt_util.utcnow(), ) + except ElviaError.AuthError: + raise except ElviaError.ElviaException as err: LOGGER.error("Error fetching data: %s", err) return diff --git a/homeassistant/components/elvia/strings.json b/homeassistant/components/elvia/strings.json index 5e64048813de..e964b06769e6 100644 --- a/homeassistant/components/elvia/strings.json +++ b/homeassistant/components/elvia/strings.json @@ -2,13 +2,24 @@ "config": { "abort": { "metering_point_id_already_configured": "Metering point with ID `{metering_point_id}` is already configured.", - "no_metering_points": "The provided API token has no metering points." + "no_metering_points": "The provided API token has no metering points.", + "wrong_account": "The API token does not give access to the metering point of this entry." }, "error": { "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", "unknown": "[%key:common::config_flow::error::unknown%]" }, "step": { + "reauth_confirm": { + "data": { + "api_token": "[%key:common::config_flow::data::api_token%]" + }, + "data_description": { + "api_token": "The new meter value API token from Elvia." + }, + "description": "The Elvia API token is no longer valid. Enter a new one.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "select_meter": { "data": { "metering_point_id": "Select your metering point ID" @@ -25,6 +36,9 @@ "exceptions": { "import_failed": { "message": "Failed to import meter values from Elvia" + }, + "invalid_auth": { + "message": "Authentication with Elvia failed" } } } diff --git a/tests/components/elvia/test_config_flow.py b/tests/components/elvia/test_config_flow.py index 55293a5cc87e..441f4760d869 100644 --- a/tests/components/elvia/test_config_flow.py +++ b/tests/components/elvia/test_config_flow.py @@ -1,5 +1,6 @@ """Test the Elvia config flow.""" +from typing import Any from unittest.mock import AsyncMock, patch from elvia import error as ElviaError @@ -238,3 +239,146 @@ async def test_form_exceptions( with pytest.raises(UnknownFlow): hass.config_entries.flow.async_get(result["flow_id"]) + + +@pytest.mark.usefixtures("recorder_mock") +async def test_reauth( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, +) -> None: + """Test a successful reauthentication.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "old-token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + result = await entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + return_value={ + "meteringpoints": [ + {"meteringPointId": "5678"}, + {"meteringPointId": "1234"}, + ] + }, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_API_TOKEN: TEST_API_TOKEN}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert entry.data == { + CONF_API_TOKEN: TEST_API_TOKEN, + CONF_METERING_POINT_ID: "1234", + } + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.parametrize( + ("side_effect", "base_error"), + [ + pytest.param( + ElviaError.AuthError("Boom", 403, {}, ""), "invalid_auth", id="auth" + ), + pytest.param( + ElviaError.ElviaServerException("Boom", 500, {}, ""), + "unknown", + id="server", + ), + pytest.param(ElviaError.ElviaClientException("Boom"), "unknown", id="client"), + ], +) +@pytest.mark.usefixtures("recorder_mock") +async def test_reauth_errors( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + side_effect: Exception, + base_error: str, +) -> None: + """Test reauthentication errors and a successful retry.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "old-token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + result = await entry.start_reauth_flow(hass) + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + side_effect=side_effect, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_API_TOKEN: "bad-token"}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": base_error} + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + return_value={"meteringpoints": [{"meteringPointId": "1234"}]}, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_API_TOKEN: TEST_API_TOKEN}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert entry.data[CONF_API_TOKEN] == TEST_API_TOKEN + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.parametrize( + "meter_values", + [ + pytest.param( + {"meteringpoints": [{"meteringPointId": "5678"}]}, id="other_point" + ), + pytest.param({"meteringpoints": []}, id="no_points"), + pytest.param({}, id="bad_data"), + ], +) +@pytest.mark.usefixtures("recorder_mock") +async def test_reauth_wrong_account( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + meter_values: dict[str, Any], +) -> None: + """Test reauthentication aborts when the token cannot read the metering point.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "old-token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + result = await entry.start_reauth_flow(hass) + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + return_value=meter_values, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_API_TOKEN: TEST_API_TOKEN}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "wrong_account" + assert entry.data[CONF_API_TOKEN] == "old-token" + assert len(mock_setup_entry.mock_calls) == 0 diff --git a/tests/components/elvia/test_init.py b/tests/components/elvia/test_init.py index d7943a441e18..10436b423f9e 100644 --- a/tests/components/elvia/test_init.py +++ b/tests/components/elvia/test_init.py @@ -1,15 +1,17 @@ """Tests for the Elvia integration setup.""" +from datetime import timedelta from unittest.mock import patch from elvia import error as ElviaError import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed from homeassistant.components.elvia.const import CONF_METERING_POINT_ID, DOMAIN -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import CONF_API_TOKEN from homeassistant.core import HomeAssistant +from homeassistant.util import dt as dt_util @pytest.mark.usefixtures("recorder_mock") @@ -30,3 +32,84 @@ async def test_setup_import_failed(hass: HomeAssistant) -> None: assert entry.state is ConfigEntryState.SETUP_ERROR assert entry.reason == "Failed to import meter values from Elvia" + + +@pytest.mark.usefixtures("recorder_mock") +async def test_setup_auth_failed(hass: HomeAssistant) -> None: + """Test setup starts a reauth flow on an authentication error.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + side_effect=ElviaError.AuthError("Boom", 401, {}, ""), + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.SETUP_ERROR + flows = hass.config_entries.flow.async_progress() + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + assert flows[0]["context"]["entry_id"] == entry.entry_id + + +@pytest.mark.usefixtures("recorder_mock") +async def test_scheduled_import_auth_failed(hass: HomeAssistant) -> None: + """Test a scheduled import starts a reauth flow on an authentication error.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.elvia.importer.ElviaImporter.import_meter_values", + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + + with patch( + "elvia.meter_value.MeterValue.get_meter_values", + side_effect=ElviaError.AuthError("Boom", 401, {}, ""), + ): + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=61)) + await hass.async_block_till_done() + + flows = hass.config_entries.flow.async_progress() + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + assert flows[0]["context"]["entry_id"] == entry.entry_id + + +@pytest.mark.usefixtures("recorder_mock") +async def test_unload_entry(hass: HomeAssistant) -> None: + """Test the entry unloads and stops the scheduled import.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="1234", + data={CONF_API_TOKEN: "token", CONF_METERING_POINT_ID: "1234"}, + ) + entry.add_to_hass(hass) + + with patch( + "homeassistant.components.elvia.importer.ElviaImporter.import_meter_values", + ) as mock_import: + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.NOT_LOADED + + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=61)) + await hass.async_block_till_done() + + assert mock_import.call_count == 1