diff --git a/homeassistant/components/snoo/__init__.py b/homeassistant/components/snoo/__init__.py index 50fd4cf167f9..cb7296c544f4 100644 --- a/homeassistant/components/snoo/__init__.py +++ b/homeassistant/components/snoo/__init__.py @@ -8,9 +8,10 @@ from python_snoo.snoo import Snoo from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession +from .const import DOMAIN from .coordinator import SnooConfigEntry, SnooCoordinator _LOGGER = logging.getLogger(__name__) @@ -36,7 +37,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: SnooConfigEntry) -> None try: await snoo.authorize() - except (SnooAuthException, InvalidSnooAuth) as ex: + except InvalidSnooAuth as ex: + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from ex + except SnooAuthException as ex: raise ConfigEntryNotReady from ex try: devices = await snoo.get_devices() diff --git a/homeassistant/components/snoo/config_flow.py b/homeassistant/components/snoo/config_flow.py index 7fd94e0214ac..fdcf227df1e6 100644 --- a/homeassistant/components/snoo/config_flow.py +++ b/homeassistant/components/snoo/config_flow.py @@ -1,5 +1,6 @@ """Config flow for the Happiest Baby Snoo integration.""" +from collections.abc import Mapping import logging from typing import Any, override @@ -23,12 +24,43 @@ STEP_USER_DATA_SCHEMA = probatio.Schema( } ) +STEP_REAUTH_DATA_SCHEMA = probatio.Schema( + { + probatio.Required(probatio.Secret(CONF_PASSWORD)): str, + } +) + class SnooConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Happiest Baby Snoo.""" VERSION = 1 + async def _async_validate_credentials( + self, username: str, password: str + ) -> tuple[str | None, dict[str, str]]: + """Validate the credentials and return the user uuid and errors.""" + hub = Snoo( + email=username, + password=password, + clientsession=async_get_clientsession(self.hass), + ) + try: + tokens = await hub.authorize() + except SnooAuthException: + return None, {"base": "cannot_connect"} + except InvalidSnooAuth: + return None, {"base": "invalid_auth"} + except Exception: + _LOGGER.exception("Unexpected exception") + return None, {"base": "unknown"} + # Authorizing starts a token refresh task that only disconnect cancels + await hub.disconnect() + user_uuid: str = jwt.decode( + tokens.aws_access, options={"verify_signature": False} + )["username"] + return user_uuid, {} + @override async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -36,25 +68,10 @@ class SnooConfigFlow(ConfigFlow, domain=DOMAIN): """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: - hub = Snoo( - email=user_input[CONF_USERNAME], - password=user_input[CONF_PASSWORD], - clientsession=async_get_clientsession(self.hass), + user_uuid, errors = await self._async_validate_credentials( + user_input[CONF_USERNAME], user_input[CONF_PASSWORD] ) - - try: - tokens = await hub.authorize() - except SnooAuthException: - errors["base"] = "cannot_connect" - except InvalidSnooAuth: - errors["base"] = "invalid_auth" - except Exception: - _LOGGER.exception("Unexpected exception") - errors["base"] = "unknown" - else: - user_uuid = jwt.decode( - tokens.aws_access, options={"verify_signature": False} - )["username"] + if user_uuid is not None: await self.async_set_unique_id(user_uuid) self._abort_if_unique_id_configured() @@ -65,3 +82,35 @@ class SnooConfigFlow(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 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() + username = reauth_entry.data[CONF_USERNAME] + if user_input is not None: + user_uuid, errors = await self._async_validate_credentials( + username, user_input[CONF_PASSWORD] + ) + if user_uuid is not None: + await self.async_set_unique_id(user_uuid) + 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=STEP_REAUTH_DATA_SCHEMA, + description_placeholders={CONF_USERNAME: username}, + errors=errors, + ) diff --git a/homeassistant/components/snoo/quality_scale.yaml b/homeassistant/components/snoo/quality_scale.yaml index adef08ada823..df8d2b5a8858 100644 --- a/homeassistant/components/snoo/quality_scale.yaml +++ b/homeassistant/components/snoo/quality_scale.yaml @@ -46,7 +46,7 @@ rules: integration-owner: done log-when-unavailable: todo parallel-updates: todo - reauthentication-flow: todo + reauthentication-flow: done test-coverage: todo # Gold diff --git a/homeassistant/components/snoo/strings.json b/homeassistant/components/snoo/strings.json index d47e11034db1..0296e168418e 100644 --- a/homeassistant/components/snoo/strings.json +++ b/homeassistant/components/snoo/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 credentials provided belong to a different Snoo account than the one previously 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::snoo::config::step::user::data_description::password%]" + }, + "description": "The password for {username} is no longer valid. Please enter your current Snoo password.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "user": { "data": { "password": "[%key:common::config_flow::data::password%]", @@ -99,6 +110,9 @@ } }, "exceptions": { + "invalid_auth": { + "message": "[%key:common::config_flow::error::invalid_auth%]" + }, "select_failed": { "message": "Error while updating {name} to {option}" }, diff --git a/tests/components/snoo/__init__.py b/tests/components/snoo/__init__.py index 417eb4381430..90e928dc8935 100644 --- a/tests/components/snoo/__init__.py +++ b/tests/components/snoo/__init__.py @@ -16,7 +16,7 @@ from tests.common import MockConfigEntry def create_entry( hass: HomeAssistant, -) -> ConfigEntry: +) -> MockConfigEntry: """Add config entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, diff --git a/tests/components/snoo/test_config_flow.py b/tests/components/snoo/test_config_flow.py index 49e262407752..385a9cb4bacd 100644 --- a/tests/components/snoo/test_config_flow.py +++ b/tests/components/snoo/test_config_flow.py @@ -14,6 +14,8 @@ from homeassistant.data_entry_flow import FlowResultType from . import create_entry +from tests.common import MockConfigEntry + async def test_config_flow_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, bypass_api: AsyncMock @@ -41,6 +43,7 @@ async def test_config_flow_success( } assert result["result"].unique_id == "123e4567-e89b-12d3-a456-426614174000" assert len(mock_setup_entry.mock_calls) == 1 + bypass_api.disconnect.assert_awaited_once() @pytest.mark.parametrize( @@ -114,3 +117,82 @@ async def test_account_already_configured( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth(hass: HomeAssistant, bypass_api: AsyncMock) -> None: + """Test a successful reauthentication flow.""" + entry = create_entry(hass) + result = await 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 entry.data == { + CONF_USERNAME: "test-username", + CONF_PASSWORD: "new-password", + } + bypass_api.disconnect.assert_awaited_once() + + +@pytest.mark.usefixtures("mock_setup_entry") +@pytest.mark.parametrize( + ("exception", "error_msg"), + [ + pytest.param(InvalidSnooAuth, "invalid_auth", id="invalid_auth"), + pytest.param(SnooAuthException, "cannot_connect", id="cannot_connect"), + pytest.param(Exception, "unknown", id="unknown"), + ], +) +async def test_reauth_errors( + hass: HomeAssistant, + bypass_api: AsyncMock, + exception: type[Exception], + error_msg: str, +) -> None: + """Test reauthentication errors and recovery.""" + entry = create_entry(hass) + result = await entry.start_reauth_flow(hass) + + bypass_api.authorize.side_effect = exception + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_PASSWORD: "new-password"} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": error_msg} + + bypass_api.authorize.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" + assert entry.data[CONF_PASSWORD] == "new-password" + + +@pytest.mark.usefixtures("mock_setup_entry", "bypass_api") +async def test_reauth_unique_id_mismatch(hass: HomeAssistant) -> None: + """Test reauthentication aborts when the credentials belong to another account.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="test-username", + data={CONF_USERNAME: "test-username", CONF_PASSWORD: "sample"}, + unique_id="other-account-uuid", + ) + entry.add_to_hass(hass) + result = await entry.start_reauth_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_PASSWORD: "new-password"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert entry.data[CONF_PASSWORD] == "sample" diff --git a/tests/components/snoo/test_init.py b/tests/components/snoo/test_init.py index 34cd9243429d..799263523abb 100644 --- a/tests/components/snoo/test_init.py +++ b/tests/components/snoo/test_init.py @@ -2,10 +2,10 @@ from unittest.mock import AsyncMock -from python_snoo.exceptions import SnooAuthException +from python_snoo.exceptions import InvalidSnooAuth, SnooAuthException from homeassistant.components.snoo import SnooDeviceError -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.core import HomeAssistant from . import async_init_integration @@ -25,6 +25,20 @@ async def test_cannot_auth(hass: HomeAssistant, bypass_api: AsyncMock) -> None: assert entry.state is ConfigEntryState.SETUP_RETRY +async def test_invalid_auth_starts_reauth( + hass: HomeAssistant, bypass_api: AsyncMock +) -> None: + """Test that rejected credentials during setup start a reauth flow.""" + bypass_api.authorize.side_effect = InvalidSnooAuth + entry = await async_init_integration(hass) + 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 + + async def test_failed_devices(hass: HomeAssistant, bypass_api: AsyncMock) -> None: """Test that we are put into retry when we fail to get devices.""" bypass_api.get_devices.side_effect = SnooDeviceError