From acf0303bd944393aa7a283ca97aed5a5a5cae6af Mon Sep 17 00:00:00 2001 From: Yoav Mor Date: Fri, 25 Sep 2026 17:18:11 +0300 Subject: [PATCH] Add Besen reauthentication flow (#182599) --- homeassistant/components/besen/config_flow.py | 49 ++++++++ homeassistant/components/besen/coordinator.py | 4 + .../components/besen/quality_scale.yaml | 4 +- homeassistant/components/besen/strings.json | 10 ++ tests/components/besen/test_config_flow.py | 110 +++++++++++++++++- tests/components/besen/test_init.py | 40 ++++++- 6 files changed, 211 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/besen/config_flow.py b/homeassistant/components/besen/config_flow.py index 6b91618ea193..0745ebd5fded 100644 --- a/homeassistant/components/besen/config_flow.py +++ b/homeassistant/components/besen/config_flow.py @@ -1,5 +1,6 @@ """Config flow for Besen.""" +from collections.abc import Mapping import logging from typing import TYPE_CHECKING, Any, override @@ -46,6 +47,8 @@ PIN_ONLY_SCHEMA = probatio.Schema( } ) +REAUTH_SCHEMA = probatio.Schema({probatio.Required(CONF_PIN): PIN_SCHEMA}) + def _user_schema( discoveries: dict[str, BluetoothServiceInfoBleak], @@ -245,3 +248,49 @@ class BesenConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): data_schema=_user_schema(self._discovered_devices), errors=errors, ) + + async def async_step_reauth( + self, + entry_data: Mapping[str, Any], + ) -> ConfigFlowResult: + """Handle a PIN rejected by a configured charger.""" + + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, + user_input: dict[str, Any] | None = None, + ) -> ConfigFlowResult: + """Confirm the current PIN of a configured charger.""" + + errors: dict[str, str] = {} + if user_input is not None: + entry = self._get_reauth_entry() + pin = user_input[CONF_PIN] + try: + await _async_validate_input( + self.hass, + address=entry.data[CONF_ADDRESS], + pin=pin, + name=entry.data[CONF_NAME], + ) + except InvalidAuth: + errors["base"] = "invalid_auth" + except NoConnectablePath: + errors["base"] = "no_connectable_path" + except CannotConnect: + errors["base"] = "cannot_connect" + except Exception: + _LOGGER.exception("Unexpected Besen reauthentication error") + errors["base"] = "unknown" + else: + return self.async_update_reload_and_abort( + entry, + data_updates={CONF_PIN: pin}, + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=REAUTH_SCHEMA, + errors=errors, + ) diff --git a/homeassistant/components/besen/coordinator.py b/homeassistant/components/besen/coordinator.py index d9d13e3cd78e..a9786ab1a981 100644 --- a/homeassistant/components/besen/coordinator.py +++ b/homeassistant/components/besen/coordinator.py @@ -24,6 +24,8 @@ _LOGGER = logging.getLogger(__name__) class BesenCoordinator(DataUpdateCoordinator[BesenData]): """Coordinate Besen state updates.""" + config_entry: BesenConfigEntry + def __init__( self, hass: HomeAssistant, @@ -79,6 +81,8 @@ class BesenCoordinator(DataUpdateCoordinator[BesenData]): """Publish a client state update.""" self.async_set_updated_data(data) + if data.auth_failed: + self.config_entry.async_start_reauth(self.hass) async def async_start_charging(self) -> None: """Start charging.""" diff --git a/homeassistant/components/besen/quality_scale.yaml b/homeassistant/components/besen/quality_scale.yaml index 02a8a8167a4b..6412a5beb06d 100644 --- a/homeassistant/components/besen/quality_scale.yaml +++ b/homeassistant/components/besen/quality_scale.yaml @@ -47,9 +47,7 @@ rules: integration-owner: done log-when-unavailable: done parallel-updates: done - reauthentication-flow: - status: todo - comment: Split into a follow-up PR after the initial integration lands. + reauthentication-flow: done test-coverage: done # Gold diff --git a/homeassistant/components/besen/strings.json b/homeassistant/components/besen/strings.json index b7dcb6669242..51e205ec5acb 100644 --- a/homeassistant/components/besen/strings.json +++ b/homeassistant/components/besen/strings.json @@ -23,6 +23,16 @@ "description": "Enter the 6-digit Bluetooth PIN for this charger.", "title": "Set up Besen" }, + "reauth_confirm": { + "data": { + "pin": "[%key:common::config_flow::data::pin%]" + }, + "data_description": { + "pin": "[%key:component::besen::config::step::user::data_description::pin%]" + }, + "description": "The charger rejected the saved Bluetooth PIN. Enter its current 6-digit PIN.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "user": { "data": { "address": "[%key:common::config_flow::data::device%]", diff --git a/tests/components/besen/test_config_flow.py b/tests/components/besen/test_config_flow.py index d7ac7ddca709..bfa5b4519cf8 100644 --- a/tests/components/besen/test_config_flow.py +++ b/tests/components/besen/test_config_flow.py @@ -1,6 +1,6 @@ """Tests for Besen config flow.""" -from unittest.mock import Mock +from unittest.mock import AsyncMock, Mock from besen.exceptions import CannotConnect, InvalidAuth from probatio import to_field_list @@ -24,6 +24,8 @@ from .conftest import ( from tests.common import MockConfigEntry from tests.components.bluetooth import generate_advertisement_data, generate_ble_device +NEW_PIN = "654321" + def _discovery(name: str | None = FIXTURE_NAME) -> BluetoothServiceInfoBleak: """Return Bluetooth discovery info.""" @@ -426,3 +428,109 @@ async def test_user_step_ignores_bluetooth_flow_in_progress( ) _assert_create_entry(result) + + +async def test_reauth_flow( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_besen_client: Mock, + mock_setup_entry: AsyncMock, +) -> None: + """Test reauthentication updates the PIN and reloads the 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_PIN: NEW_PIN}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_ADDRESS: FIXTURE_ADDRESS, + CONF_NAME: FIXTURE_NAME, + CONF_PIN: NEW_PIN, + } + mock_besen_client.async_start.assert_awaited_once() + mock_besen_client.async_stop.assert_awaited_once() + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + pytest.param(InvalidAuth("bad pin"), "invalid_auth", id="invalid-auth"), + pytest.param(CannotConnect("cannot connect"), "cannot_connect", id="connect"), + pytest.param(RuntimeError("boom"), "unknown", id="unknown"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_flow_errors_can_recover( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_besen_client: Mock, + exception: Exception, + error: str, +) -> None: + """Test reauthentication errors keep the saved PIN and can recover.""" + + mock_besen_client.async_start.side_effect = [exception, None] + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reauth_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PIN: NEW_PIN}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": error} + assert mock_config_entry.data[CONF_PIN] == FIXTURE_PIN + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PIN: NEW_PIN}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data[CONF_PIN] == NEW_PIN + + +@pytest.mark.usefixtures("mock_besen_client", "mock_setup_entry") +async def test_reauth_flow_no_connectable_path_can_recover( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ble_device: Mock, +) -> None: + """Test reauthentication recovers after a path becomes available.""" + + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reauth_flow(hass) + + mock_ble_device.return_value = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PIN: NEW_PIN}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": "no_connectable_path"} + + mock_ble_device.return_value = _discovery().device + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_PIN: NEW_PIN}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data[CONF_PIN] == NEW_PIN diff --git a/tests/components/besen/test_init.py b/tests/components/besen/test_init.py index f8df5cac7531..0e1535bae777 100644 --- a/tests/components/besen/test_init.py +++ b/tests/components/besen/test_init.py @@ -3,10 +3,14 @@ from unittest.mock import AsyncMock, Mock, patch from besen.exceptions import CannotConnect, InvalidAuth +import pytest -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.core import HomeAssistant +from . import publish_besen_state +from .conftest import charger_state, setup_integration + from tests.common import MockConfigEntry @@ -57,7 +61,7 @@ async def test_setup_entry_auth_error_fails_setup( mock_config_entry: MockConfigEntry, mock_besen_client: Mock, ) -> None: - """Test setup maps invalid auth to a config-entry auth failure.""" + """Test setup maps invalid auth to a config-entry auth failure and reauth.""" mock_besen_client.async_start.side_effect = InvalidAuth("bad pin") mock_config_entry.add_to_hass(hass) @@ -66,10 +70,42 @@ async def test_setup_entry_auth_error_fails_setup( await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) + assert len(list(flows)) == 1 mock_besen_client.add_listener.return_value.assert_called_once_with() mock_besen_client.async_stop.assert_awaited_once() +@pytest.mark.parametrize( + ("auth_failed", "reauth_flows"), + [ + pytest.param(True, 1, id="pin-rejected"), + pytest.param(False, 0, id="connection-lost"), + ], +) +async def test_runtime_pin_rejection_starts_reauth( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_besen_client: Mock, + auth_failed: bool, + reauth_flows: int, +) -> None: + """Test only a PIN rejected after setup starts reauthentication.""" + + await setup_integration(hass, mock_config_entry) + + publish_besen_state( + mock_besen_client, + charger_state(available=False, authenticated=False).updated( + auth_failed=auth_failed + ), + ) + await hass.async_block_till_done() + + flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) + assert len(list(flows)) == reauth_flows + + async def test_setup_entry_connect_error_retries( hass: HomeAssistant, mock_config_entry: MockConfigEntry,