diff --git a/homeassistant/components/smartyplants/config_flow.py b/homeassistant/components/smartyplants/config_flow.py index d7257948b10c..7446963e6e1a 100644 --- a/homeassistant/components/smartyplants/config_flow.py +++ b/homeassistant/components/smartyplants/config_flow.py @@ -1,5 +1,6 @@ """Config flow for SmartyPlants — this is what replaces configuration.yaml.""" +from collections.abc import Mapping from typing import Any, override import probatio @@ -123,3 +124,33 @@ class SmartyPlantsConfigFlow(ConfigFlow, domain=DOMAIN): data_schema=STEP_WEBHOOK_SCHEMA, description_placeholders={"webhook_url": webhook_url}, ) + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle a rejected API key.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Prompt for a new API key for the same account.""" + errors: dict[str, str] = {} + + if user_input is not None: + error, account_id = await self._async_validate(user_input[CONF_API_KEY]) + if error: + errors["base"] = error + else: + await self.async_set_unique_id(account_id) + self._abort_if_unique_id_mismatch() + return self.async_update_reload_and_abort( + self._get_reauth_entry(), + data_updates={CONF_API_KEY: user_input[CONF_API_KEY]}, + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=CREDENTIALS_SCHEMA, + errors=errors, + ) diff --git a/homeassistant/components/smartyplants/coordinator.py b/homeassistant/components/smartyplants/coordinator.py index ce8cddde0ae3..39e869a74f81 100644 --- a/homeassistant/components/smartyplants/coordinator.py +++ b/homeassistant/components/smartyplants/coordinator.py @@ -15,6 +15,7 @@ from pysmartyplants import ( from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN @@ -54,9 +55,7 @@ class SmartyPlantsCoordinator(DataUpdateCoordinator[dict[str, Sensor]]): try: sensors = await self.client.async_get_sensors() except SmartyPlantsAuthError as err: - # Reported as an update failure rather than starting a re-auth - # flow, which this integration does not offer yet. - raise UpdateFailed( + raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth" ) from err except SmartyPlantsForbiddenError as err: diff --git a/homeassistant/components/smartyplants/quality_scale.yaml b/homeassistant/components/smartyplants/quality_scale.yaml index 2bd805a775ed..6420ea4a1d52 100644 --- a/homeassistant/components/smartyplants/quality_scale.yaml +++ b/homeassistant/components/smartyplants/quality_scale.yaml @@ -59,7 +59,7 @@ rules: status: done comment: Handled by the coordinator. parallel-updates: done - reauthentication-flow: todo + reauthentication-flow: done test-coverage: done # Gold diff --git a/homeassistant/components/smartyplants/strings.json b/homeassistant/components/smartyplants/strings.json index 58d70032a85c..921076a6fcb5 100644 --- a/homeassistant/components/smartyplants/strings.json +++ b/homeassistant/components/smartyplants/strings.json @@ -1,7 +1,8 @@ { "config": { "abort": { - "already_configured": "[%key:common::config_flow::abort::already_configured_account%]" + "already_configured": "[%key:common::config_flow::abort::already_configured_account%]", + "unique_id_mismatch": "The API key belongs to a different SmartyPlants account. Enter a key for the account that was set up originally." }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", @@ -9,6 +10,15 @@ "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]" }, "step": { + "reauth_confirm": { + "data": { + "api_key": "[%key:common::config_flow::data::api_key%]" + }, + "data_description": { + "api_key": "[%key:component::smartyplants::config::step::user::data_description::api_key%]" + }, + "description": "SmartyPlants rejected the stored API key. Create a new key in the SmartyPlants app, under Settings, and enter it below." + }, "user": { "data": { "api_key": "[%key:common::config_flow::data::api_key%]" @@ -55,7 +65,7 @@ "message": "SmartyPlants refused the request: {error}" }, "invalid_auth": { - "message": "The SmartyPlants API key was rejected. Remove the integration and add it again with a new key." + "message": "The SmartyPlants API key was rejected. Re-authenticate the integration with a new key." } } } diff --git a/tests/components/smartyplants/test_config_flow.py b/tests/components/smartyplants/test_config_flow.py index e5a37eee5c00..1831a0aeb6e7 100644 --- a/tests/components/smartyplants/test_config_flow.py +++ b/tests/components/smartyplants/test_config_flow.py @@ -17,11 +17,12 @@ from homeassistant.core import HomeAssistant from homeassistant.core_config import async_process_ha_core_config from homeassistant.data_entry_flow import FlowResultType -from .conftest import ACCOUNT_ID, API_KEY +from .conftest import ACCOUNT_ID, API_KEY, WEBHOOK_ID, WEBHOOK_SECRET from tests.common import MockConfigEntry USER_INPUT = {CONF_API_KEY: API_KEY} +NEW_API_KEY = "sp_rotated_key_87654321" @pytest.fixture @@ -151,3 +152,84 @@ async def test_no_external_url_skips_webhook_step(hass: HomeAssistant) -> None: assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == ACCOUNT_ID assert CONF_WEBHOOK_SECRET not in result["data"] + + +@pytest.mark.usefixtures("mock_smartyplants_client", "mock_setup_entry") +async def test_reauth(hass: HomeAssistant, mock_config_entry: MockConfigEntry) -> None: + """Test reauthentication stores the new key and keeps the rest.""" + 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_API_KEY: NEW_API_KEY} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_API_KEY: NEW_API_KEY, + CONF_WEBHOOK_ID: WEBHOOK_ID, + CONF_WEBHOOK_SECRET: WEBHOOK_SECRET, + } + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + pytest.param(SmartyPlantsAuthError("boom"), "invalid_auth", id="auth"), + pytest.param( + SmartyPlantsConnectionError("boom"), "cannot_connect", id="connection" + ), + pytest.param(SmartyPlantsForbiddenError("boom"), "forbidden", id="forbidden"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_errors_then_recovers( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_smartyplants_client: AsyncMock, + error: SmartyPlantsError, + expected: str, +) -> None: + """Test a failed reauth check is reported and the flow can still finish.""" + mock_config_entry.add_to_hass(hass) + mock_smartyplants_client.async_verify.side_effect = error + + result = await mock_config_entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: NEW_API_KEY} + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": expected} + + mock_smartyplants_client.async_verify.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: NEW_API_KEY} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data[CONF_API_KEY] == NEW_API_KEY + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_other_account_aborts( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_smartyplants_client: AsyncMock, +) -> None: + """Test a key for a different account is refused and the old key kept.""" + mock_config_entry.add_to_hass(hass) + mock_smartyplants_client.async_verify.return_value = "acct-other" + + result = await mock_config_entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: NEW_API_KEY} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert mock_config_entry.data[CONF_API_KEY] == API_KEY diff --git a/tests/components/smartyplants/test_init.py b/tests/components/smartyplants/test_init.py index 6231745629d8..b4bc74c2ac79 100644 --- a/tests/components/smartyplants/test_init.py +++ b/tests/components/smartyplants/test_init.py @@ -2,21 +2,23 @@ from unittest.mock import AsyncMock +from freezegun.api import FrozenDateTimeFactory from pysmartyplants import ( SmartyPlantsAuthError, SmartyPlantsConnectionError, SmartyPlantsError, + SmartyPlantsForbiddenError, ) import pytest -from homeassistant.components.smartyplants.const import DOMAIN -from homeassistant.config_entries import ConfigEntryState +from homeassistant.components.smartyplants.const import DEFAULT_SCAN_INTERVAL, DOMAIN +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.core import HomeAssistant from . import setup_integration -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_fire_time_changed @pytest.mark.usefixtures("mock_smartyplants_client") @@ -36,7 +38,7 @@ async def test_load_unload_entry( "error", [ pytest.param(SmartyPlantsConnectionError("boom"), id="connection"), - pytest.param(SmartyPlantsAuthError("nope"), id="auth"), + pytest.param(SmartyPlantsForbiddenError("nope"), id="forbidden"), ], ) async def test_setup_retries_when_first_poll_fails( @@ -51,6 +53,49 @@ async def test_setup_retries_when_first_poll_fails( await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert not hass.config_entries.flow.async_progress() + + +async def test_setup_auth_failure_starts_reauth( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_smartyplants_client: AsyncMock, +) -> None: + """Test a rejected key during setup starts a reauth flow.""" + mock_smartyplants_client.async_get_sensors.side_effect = SmartyPlantsAuthError( + "nope" + ) + + await setup_integration(hass, mock_config_entry) + + 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_poll_auth_failure_starts_reauth( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_smartyplants_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a key rejected on a scheduled poll starts a reauth flow.""" + await setup_integration(hass, mock_config_entry) + assert not hass.config_entries.flow.async_progress() + + mock_smartyplants_client.async_get_sensors.side_effect = SmartyPlantsAuthError( + "nope" + ) + freezer.tick(DEFAULT_SCAN_INTERVAL) + 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 @pytest.mark.usefixtures("mock_smartyplants_client") diff --git a/tests/components/smartyplants/test_sensor.py b/tests/components/smartyplants/test_sensor.py index 8b1f84ed81a7..8f63a03e339b 100644 --- a/tests/components/smartyplants/test_sensor.py +++ b/tests/components/smartyplants/test_sensor.py @@ -5,7 +5,6 @@ from unittest.mock import AsyncMock from freezegun.api import FrozenDateTimeFactory from pysmartyplants import ( - SmartyPlantsAuthError, SmartyPlantsConnectionError, SmartyPlantsError, SmartyPlantsForbiddenError, @@ -155,7 +154,6 @@ async def test_sensor_removed_from_account( {"error": "boom"}, id="connection", ), - pytest.param(SmartyPlantsAuthError("nope"), "invalid_auth", None, id="auth"), pytest.param( SmartyPlantsForbiddenError( "This API key does not allow requests from 198.51.100.7."