From 93e9575547b745fad7523da712e021a0e965dd4f Mon Sep 17 00:00:00 2001 From: mcisk Date: Thu, 9 Apr 2026 17:30:53 +0200 Subject: [PATCH] Add reauthentication flow to Autoskope integration (#167688) --- .../components/autoskope/__init__.py | 5 +- .../components/autoskope/config_flow.py | 75 ++++++++++++++++--- .../components/autoskope/quality_scale.yaml | 5 +- .../components/autoskope/strings.json | 12 ++- .../components/autoskope/test_config_flow.py | 69 +++++++++++++++++ 5 files changed, 146 insertions(+), 20 deletions(-) diff --git a/homeassistant/components/autoskope/__init__.py b/homeassistant/components/autoskope/__init__.py index a269976dc350..084755cb5487 100644 --- a/homeassistant/components/autoskope/__init__.py +++ b/homeassistant/components/autoskope/__init__.py @@ -8,7 +8,7 @@ from autoskope_client.models import CannotConnect, InvalidAuth from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, Platform from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_create_clientsession from .const import DEFAULT_HOST @@ -31,8 +31,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: AutoskopeConfigEntry) -> try: await api.connect() except InvalidAuth as err: - # Raise ConfigEntryError until reauth flow is implemented (then ConfigEntryAuthFailed) - raise ConfigEntryError( + raise ConfigEntryAuthFailed( "Authentication failed, please check credentials" ) from err except CannotConnect as err: diff --git a/homeassistant/components/autoskope/config_flow.py b/homeassistant/components/autoskope/config_flow.py index 3f141b4663f5..0f30fe9ada7b 100644 --- a/homeassistant/components/autoskope/config_flow.py +++ b/homeassistant/components/autoskope/config_flow.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Mapping from typing import Any from autoskope_client.api import AutoskopeApi @@ -39,12 +40,39 @@ STEP_USER_DATA_SCHEMA = vol.Schema( } ) +STEP_REAUTH_DATA_SCHEMA = vol.Schema( + { + vol.Required(CONF_PASSWORD): TextSelector( + TextSelectorConfig(type=TextSelectorType.PASSWORD) + ), + } +) + class AutoskopeConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Autoskope.""" VERSION = 1 + async def _async_validate_credentials( + self, host: str, username: str, password: str, errors: dict[str, str] + ) -> bool: + """Validate credentials against the Autoskope API.""" + try: + async with AutoskopeApi( + host=host, + username=username, + password=password, + ): + pass + except CannotConnect: + errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" + else: + return True + return False + async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -63,18 +91,9 @@ class AutoskopeConfigFlow(ConfigFlow, domain=DOMAIN): await self.async_set_unique_id(f"{username}@{host}") self._abort_if_unique_id_configured() - try: - async with AutoskopeApi( - host=host, - username=username, - password=user_input[CONF_PASSWORD], - ): - pass - except CannotConnect: - errors["base"] = "cannot_connect" - except InvalidAuth: - errors["base"] = "invalid_auth" - else: + if await self._async_validate_credentials( + host, username, user_input[CONF_PASSWORD], errors + ): return self.async_create_entry( title=f"Autoskope ({username})", data={ @@ -87,3 +106,35 @@ class AutoskopeConfigFlow(ConfigFlow, domain=DOMAIN): return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle initiation of re-authentication.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle re-authentication with new credentials.""" + errors: dict[str, str] = {} + + if user_input is not None: + reauth_entry = self._get_reauth_entry() + + if await self._async_validate_credentials( + reauth_entry.data[CONF_HOST], + reauth_entry.data[CONF_USERNAME], + user_input[CONF_PASSWORD], + errors, + ): + 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=STEP_REAUTH_DATA_SCHEMA, + errors=errors, + ) diff --git a/homeassistant/components/autoskope/quality_scale.yaml b/homeassistant/components/autoskope/quality_scale.yaml index c0af808b0996..264d9c35e7a6 100644 --- a/homeassistant/components/autoskope/quality_scale.yaml +++ b/homeassistant/components/autoskope/quality_scale.yaml @@ -39,10 +39,7 @@ rules: integration-owner: done log-when-unavailable: todo parallel-updates: done - reauthentication-flow: - status: todo - comment: | - Reauthentication flow removed for initial PR, will be added in follow-up. + reauthentication-flow: done test-coverage: done # Gold devices: done diff --git a/homeassistant/components/autoskope/strings.json b/homeassistant/components/autoskope/strings.json index d3a05f9f2865..18e83c0866c3 100644 --- a/homeassistant/components/autoskope/strings.json +++ b/homeassistant/components/autoskope/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%]", + "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]" }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", @@ -10,6 +11,15 @@ "unknown": "[%key:common::config_flow::error::unknown%]" }, "step": { + "reauth_confirm": { + "data": { + "password": "[%key:common::config_flow::data::password%]" + }, + "data_description": { + "password": "The new password for your Autoskope account." + }, + "description": "Please re-enter your password for your Autoskope account." + }, "user": { "data": { "password": "[%key:common::config_flow::data::password%]", diff --git a/tests/components/autoskope/test_config_flow.py b/tests/components/autoskope/test_config_flow.py index de4f6b01b72a..14aabb35a168 100644 --- a/tests/components/autoskope/test_config_flow.py +++ b/tests/components/autoskope/test_config_flow.py @@ -165,3 +165,72 @@ async def test_custom_host( assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_HOST] == "https://custom.autoskope.server" assert result["result"].unique_id == "test_user@https://custom.autoskope.server" + + +async def test_reauth_flow( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_autoskope_client: AsyncMock, + mock_setup_entry: AsyncMock, +) -> None: + """Test reauth flow updates password and reloads entry.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PASSWORD: "new_password"}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_USERNAME: "test_user", + CONF_PASSWORD: "new_password", + CONF_HOST: DEFAULT_HOST, + } + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (InvalidAuth("Invalid credentials"), "invalid_auth"), + (CannotConnect("Connection failed"), "cannot_connect"), + ], +) +async def test_reauth_flow_errors( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_autoskope_client: AsyncMock, + mock_setup_entry: AsyncMock, + exception: Exception, + error: str, +) -> None: + """Test reauth flow error handling with recovery.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + + mock_autoskope_client.__aenter__.side_effect = exception + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PASSWORD: "wrong_password"}, + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + + # Recovery: clear the error and retry + mock_autoskope_client.__aenter__.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PASSWORD: "new_password"}, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful"