From 994aa2eb58f90489a64714106ee6b0fc8d052df4 Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Wed, 14 Oct 2026 02:55:45 +0200 Subject: [PATCH] Add reauthentication flow to Flow-it (#186296) Co-authored-by: Claude --- .../components/flow_it/config_flow.py | 84 ++++++++++++++----- .../components/flow_it/quality_scale.yaml | 2 +- homeassistant/components/flow_it/strings.json | 13 ++- tests/components/flow_it/test_config_flow.py | 83 +++++++++++++++++- tests/components/flow_it/test_init.py | 44 +++++++++- 5 files changed, 201 insertions(+), 25 deletions(-) diff --git a/homeassistant/components/flow_it/config_flow.py b/homeassistant/components/flow_it/config_flow.py index 19bc11f30939..4a5a793788ef 100644 --- a/homeassistant/components/flow_it/config_flow.py +++ b/homeassistant/components/flow_it/config_flow.py @@ -1,5 +1,6 @@ """Config flow for Flow-it integration.""" +from collections.abc import Mapping import logging from typing import TYPE_CHECKING, Any, override @@ -49,6 +50,21 @@ class FlowItConfigFlow(ConfigFlow, domain=DOMAIN): """Initialize the config flow.""" self._discovery_info: dict[str, Any] = {} + async def _async_validate( + self, data: dict[str, Any] + ) -> tuple[dict[str, Any] | None, dict[str, str]]: + """Validate the input and return the device info and any errors.""" + try: + info = await validate_input(self.hass, data) + except FlowItAuthError: + return None, {"base": "invalid_auth"} + except FlowItConnectionError: + return None, {"base": "cannot_connect"} + except Exception: + _LOGGER.exception("Unexpected exception") + return None, {"base": "unknown"} + return info, {} + @override async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -62,16 +78,8 @@ class FlowItConfigFlow(ConfigFlow, domain=DOMAIN): host = str(URL.build(scheme="http", host=host)) user_input[CONF_HOST] = host - try: - info = await validate_input(self.hass, user_input) - except FlowItAuthError: - errors["base"] = "invalid_auth" - except FlowItConnectionError: - errors["base"] = "cannot_connect" - except Exception: - _LOGGER.exception("Unexpected exception") - errors["base"] = "unknown" - else: + info, errors = await self._async_validate(user_input) + if info is not None: await self.async_set_unique_id(info["mac_address"]) self._abort_if_unique_id_configured(updates=user_input) return self.async_create_entry(title=info["title"], data=user_input) @@ -115,16 +123,8 @@ class FlowItConfigFlow(ConfigFlow, domain=DOMAIN): CONF_PASSWORD: user_input[CONF_PASSWORD], } - try: - info = await validate_input(self.hass, data) - except FlowItAuthError: - errors["base"] = "invalid_auth" - except FlowItConnectionError: - errors["base"] = "cannot_connect" - except Exception: - _LOGGER.exception("Unexpected exception") - errors["base"] = "unknown" - else: + info, errors = await self._async_validate(data) + if info is not None: await self.async_set_unique_id(info["mac_address"]) self._abort_if_unique_id_configured(updates=data) return self.async_create_entry( @@ -183,3 +183,47 @@ class FlowItConfigFlow(ConfigFlow, domain=DOMAIN): self.context.update({"title_placeholders": {"name": friendly_name}}) return await self.async_step_zeroconf_confirm() + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle reauthentication.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm reauthentication with a new password.""" + errors: dict[str, str] = {} + reauth_entry = self._get_reauth_entry() + if user_input is not None: + info, errors = await self._async_validate( + {**reauth_entry.data, CONF_PASSWORD: user_input[CONF_PASSWORD]} + ) + if info is not None: + await self.async_set_unique_id(info["mac_address"]) + self._abort_if_unique_id_mismatch() + return self.async_update_reload_and_abort( + reauth_entry, + data_updates={CONF_PASSWORD: user_input[CONF_PASSWORD]}, + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=probatio.Schema( + { + probatio.Required(probatio.Secret(CONF_PASSWORD)): TextSelector( + TextSelectorConfig( + type=TextSelectorType.PASSWORD, + autocomplete="current-password", + ) + ), + } + ), + errors=errors, + description_placeholders={ + "name": reauth_entry.title, + CONF_USERNAME: reauth_entry.data[CONF_USERNAME], + CONF_HOST: reauth_entry.data[CONF_HOST], + }, + ) diff --git a/homeassistant/components/flow_it/quality_scale.yaml b/homeassistant/components/flow_it/quality_scale.yaml index 682923ab3997..b48139bb5f64 100644 --- a/homeassistant/components/flow_it/quality_scale.yaml +++ b/homeassistant/components/flow_it/quality_scale.yaml @@ -40,7 +40,7 @@ rules: integration-owner: todo log-when-unavailable: todo parallel-updates: todo - reauthentication-flow: todo + reauthentication-flow: done test-coverage: todo # Gold diff --git a/homeassistant/components/flow_it/strings.json b/homeassistant/components/flow_it/strings.json index f3075463121e..0096f58bd686 100644 --- a/homeassistant/components/flow_it/strings.json +++ b/homeassistant/components/flow_it/strings.json @@ -1,7 +1,8 @@ { "config": { "abort": { - "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", + "unique_id_mismatch": "The device you are trying to reauthenticate is not the same as the one configured." }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", @@ -9,6 +10,16 @@ "unknown": "[%key:common::config_flow::error::unknown%]" }, "step": { + "reauth_confirm": { + "data": { + "password": "[%key:common::config_flow::data::password%]" + }, + "data_description": { + "password": "[%key:component::flow_it::config::step::user::data_description::password%]" + }, + "description": "The password for user {username} on {host} is no longer valid. Please enter the current password.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "user": { "data": { "host": "[%key:common::config_flow::data::host%]", diff --git a/tests/components/flow_it/test_config_flow.py b/tests/components/flow_it/test_config_flow.py index 9e3cacc49250..389155d8d2c5 100644 --- a/tests/components/flow_it/test_config_flow.py +++ b/tests/components/flow_it/test_config_flow.py @@ -1,7 +1,7 @@ """Test the Flow-it config flow.""" from ipaddress import ip_address -from unittest.mock import AsyncMock +from unittest.mock import ANY, AsyncMock from flow_it_api.exceptions import FlowItAuthError, FlowItConnectionError import pytest @@ -238,3 +238,84 @@ async def test_user_flow_with_http( assert result["title"] == "Flow-it Device" assert result["data"] == {**USER_INPUT, "host": f"http://{USER_INPUT['host']}"} assert result["result"].unique_id == "001122334455" + + +async def test_reauth_flow( + hass: HomeAssistant, mock_flow_it: AsyncMock, mock_config_entry: MockConfigEntry +) -> None: + """Test reauthentication flow.""" + result = await mock_config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["description_placeholders"] == { + "name": "Flow-it Device", + "username": "api", + "host": "http://1.1.1.1", + } + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "new-password"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + "host": "http://1.1.1.1", + "username": "api", + "password": "new-password", + } + mock_flow_it.assert_called_with( + "http://1.1.1.1", "new-password", "api", session=ANY + ) + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + pytest.param(FlowItAuthError, "invalid_auth", id="invalid_auth"), + pytest.param(FlowItConnectionError, "cannot_connect", id="cannot_connect"), + pytest.param(Exception, "unknown", id="unknown"), + ], +) +async def test_reauth_flow_exceptions( + hass: HomeAssistant, + mock_flow_it: AsyncMock, + mock_config_entry: MockConfigEntry, + exception: type[Exception], + error: str, +) -> None: + """Test reauthentication flow handles errors and recovers.""" + result = await mock_config_entry.start_reauth_flow(hass) + + mock_flow_it.return_value.get_info.side_effect = exception + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "new-password"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + + mock_flow_it.return_value.get_info.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "new-password"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data["password"] == "new-password" + + +async def test_reauth_flow_unique_id_mismatch( + hass: HomeAssistant, mock_flow_it: AsyncMock, mock_config_entry: MockConfigEntry +) -> None: + """Test reauthentication aborts when a different device responds.""" + result = await mock_config_entry.start_reauth_flow(hass) + + mock_flow_it.return_value.state.name = "665544332211" + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "new-password"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert mock_config_entry.data["password"] == "test-password" diff --git a/tests/components/flow_it/test_init.py b/tests/components/flow_it/test_init.py index 9b2473dca4ad..0f6ea9a2f40d 100644 --- a/tests/components/flow_it/test_init.py +++ b/tests/components/flow_it/test_init.py @@ -1,14 +1,16 @@ """Test Flow-it integration setup and unload.""" +from datetime import timedelta from unittest.mock import AsyncMock from flow_it_api.exceptions import FlowItAuthError, FlowItConnectionError +from freezegun.api import FrozenDateTimeFactory import pytest -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.core import HomeAssistant -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_fire_time_changed async def test_setup_unload_entry( @@ -52,3 +54,41 @@ async def test_setup_exceptions( await hass.async_block_till_done() assert mock_config_entry.state == expected_state + + +async def test_setup_auth_failed_starts_reauth( + hass: HomeAssistant, mock_flow_it: AsyncMock, mock_config_entry: MockConfigEntry +) -> None: + """Test an authentication error during setup starts a reauth flow.""" + mock_flow_it.return_value.refresh_state.side_effect = FlowItAuthError + + 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_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"] == mock_config_entry.entry_id + + +async def test_update_auth_failed_starts_reauth( + hass: HomeAssistant, + mock_flow_it: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test an authentication error during a scheduled refresh starts reauth.""" + 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 + + mock_flow_it.return_value.refresh_state.side_effect = FlowItAuthError + freezer.tick(timedelta(seconds=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + flows = hass.config_entries.flow.async_progress() + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH + assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id