Add reauthentication flow to SmartyPlants (#186393)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-10-14 06:23:06 -04:00
committed by GitHub
co-authored by Claude
parent f20763554d
commit ac8d6004a6
7 changed files with 178 additions and 13 deletions
@@ -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,
)
@@ -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:
@@ -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
@@ -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."
}
}
}
@@ -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
+49 -4
View File
@@ -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")
@@ -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."