Add reauthentication flow to Liebherr integration (#161902)

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
mettolen
2026-01-31 16:12:52 +02:00
committed by GitHub
parent 0d215597f3
commit 67642e6246
7 changed files with 179 additions and 24 deletions
@@ -12,7 +12,7 @@ from pyliebherrhomeapi.exceptions import (
from homeassistant.const import CONF_API_KEY, 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_get_clientsession
from .coordinator import LiebherrConfigEntry, LiebherrCoordinator
@@ -32,7 +32,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: LiebherrConfigEntry) ->
try:
devices = await client.get_devices()
except LiebherrAuthenticationError as err:
raise ConfigEntryError("Invalid API key") from err
raise ConfigEntryAuthFailed("Invalid API key") from err
except LiebherrConnectionError as err:
raise ConfigEntryNotReady(f"Failed to connect to Liebherr API: {err}") from err
@@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
@@ -30,6 +31,25 @@ STEP_USER_DATA_SCHEMA = vol.Schema(
class LiebherrConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for liebherr."""
async def _validate_api_key(self, api_key: str) -> tuple[list, dict[str, str]]:
"""Validate the API key and return devices and errors."""
errors: dict[str, str] = {}
devices: list = []
client = LiebherrClient(
api_key=api_key,
session=async_get_clientsession(self.hass),
)
try:
devices = await client.get_devices()
except LiebherrAuthenticationError:
errors["base"] = "invalid_auth"
except LiebherrConnectionError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return devices, errors
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
@@ -40,21 +60,8 @@ class LiebherrConfigFlow(ConfigFlow, domain=DOMAIN):
self._async_abort_entries_match({CONF_API_KEY: user_input[CONF_API_KEY]})
try:
# Create a client and test the connection
client = LiebherrClient(
api_key=user_input[CONF_API_KEY],
session=async_get_clientsession(self.hass),
)
devices = await client.get_devices()
except LiebherrAuthenticationError:
errors["base"] = "invalid_auth"
except LiebherrConnectionError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
devices, errors = await self._validate_api_key(user_input[CONF_API_KEY])
if not errors:
if not devices:
return self.async_abort(reason="no_devices")
@@ -66,3 +73,31 @@ class LiebherrConfigFlow(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 re-authentication."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm re-authentication."""
errors: dict[str, str] = {}
if user_input is not None:
api_key = user_input[CONF_API_KEY].strip()
_, errors = await self._validate_api_key(api_key)
if not errors:
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={CONF_API_KEY: api_key},
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
@@ -15,7 +15,11 @@ from pyliebherrhomeapi import (
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryError,
ConfigEntryNotReady,
)
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
@@ -64,7 +68,7 @@ class LiebherrCoordinator(DataUpdateCoordinator[DeviceState]):
try:
return await self.client.get_device_state(self.device_id)
except LiebherrAuthenticationError as err:
raise ConfigEntryError("API key is no longer valid") from err
raise ConfigEntryAuthFailed("API key is no longer valid") from err
except LiebherrTimeoutError as err:
raise UpdateFailed(
f"Timeout communicating with device {self.device_id}"
@@ -36,7 +36,7 @@ rules:
integration-owner: done
log-when-unavailable: todo
parallel-updates: done
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done
# Gold
@@ -60,7 +60,9 @@ rules:
entity-translations: done
exception-translations: todo
icon-translations: todo
reconfiguration-flow: todo
reconfiguration-flow:
status: exempt
comment: The only configuration option is the API key, which is handled by the reauthentication flow.
repair-issues:
status: exempt
comment: No repair issues to implement at this time.
+11 -1
View File
@@ -2,7 +2,8 @@
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"no_devices": "No devices found for this API key"
"no_devices": "No devices found for this API key",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
@@ -11,6 +12,15 @@
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"step": {
"reauth_confirm": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
},
"data_description": {
"api_key": "[%key:component::liebherr::config::step::user::data_description::api_key%]"
},
"description": "Your API key is no longer valid. Please enter a new API key to continue."
},
"user": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
@@ -168,3 +168,67 @@ async def test_zeroconf_already_configured(
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
async def test_reauth_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_liebherr_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "reauth_confirm"
new_api_key = "new-api-key"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: new_api_key}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == new_api_key
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(LiebherrAuthenticationError("Invalid"), "invalid_auth"),
(LiebherrConnectionError("Failed"), "cannot_connect"),
(Exception("Unexpected"), "unknown"),
],
)
async def test_reauth_flow_errors_with_recovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_liebherr_client: MagicMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test reauth flow error handling with successful recovery."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "reauth_confirm"
# Trigger error
mock_liebherr_client.get_devices.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: "new-api-key"}
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": expected_error}
# Recover and complete successfully
mock_liebherr_client.get_devices.side_effect = None
new_api_key = "new-api-key-recovered"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: new_api_key}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == new_api_key
+42 -2
View File
@@ -20,6 +20,8 @@ from pyliebherrhomeapi.exceptions import (
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.liebherr.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
@@ -135,9 +137,8 @@ async def test_multi_zone_with_none_position(
[
LiebherrConnectionError("Connection failed"),
LiebherrTimeoutError("Timeout"),
LiebherrAuthenticationError("API key revoked"),
],
ids=["connection_error", "timeout_error", "auth_error"],
ids=["connection_error", "timeout_error"],
)
async def test_sensor_update_failure(
hass: HomeAssistant,
@@ -179,6 +180,45 @@ async def test_sensor_update_failure(
assert state.state == "5"
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_sensor_update_auth_failure_triggers_reauth(
hass: HomeAssistant,
mock_liebherr_client: MagicMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test authentication error triggers reauth flow."""
entity_id = "sensor.test_fridge_top_zone"
# Initial state should be available with value
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "5"
# Simulate auth error
mock_liebherr_client.get_device_state.side_effect = LiebherrAuthenticationError(
"API key revoked"
)
# Advance time to trigger coordinator refresh (60 second interval)
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Sensor should now be unavailable
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
# Config entry should be in reauth state
assert mock_config_entry.state is ConfigEntryState.LOADED
flows = hass.config_entries.flow.async_progress()
assert any(
flow["handler"] == DOMAIN and flow["context"]["source"] == "reauth"
for flow in flows
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_sensor_unavailable_when_control_missing(
hass: HomeAssistant,