From d32e9eb3236e027edbec541db85fd52b6b2d5f03 Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Wed, 14 Oct 2026 12:22:50 +0200 Subject: [PATCH] Add reauthentication flow to AirNow (#186390) Co-authored-by: Claude --- .../components/airnow/config_flow.py | 66 ++++++++++++++----- .../components/airnow/coordinator.py | 7 +- .../components/airnow/quality_scale.yaml | 2 +- homeassistant/components/airnow/strings.json | 15 +++++ tests/components/airnow/test_config_flow.py | 56 ++++++++++++++++ tests/components/airnow/test_init.py | 54 +++++++++++++++ 6 files changed, 183 insertions(+), 17 deletions(-) create mode 100644 tests/components/airnow/test_init.py diff --git a/homeassistant/components/airnow/config_flow.py b/homeassistant/components/airnow/config_flow.py index c8b939b90276..f9578043719b 100644 --- a/homeassistant/components/airnow/config_flow.py +++ b/homeassistant/components/airnow/config_flow.py @@ -1,5 +1,6 @@ """Config flow for AirNow integration.""" +from collections.abc import Mapping import logging from typing import Any, override @@ -62,7 +63,7 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN): self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" - errors = {} + errors: dict[str, str] = {} if user_input is not None: # Set a unique id based on latitude/longitude await self.async_set_unique_id( @@ -70,20 +71,7 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN): ) self._abort_if_unique_id_configured() - try: - # Validate inputs - await validate_input(self.hass, user_input) - - except CannotConnect: - errors["base"] = "cannot_connect" - except InvalidAuth: - errors["base"] = "invalid_auth" - except InvalidLocation: - errors["base"] = "invalid_location" - except Exception: - _LOGGER.exception("Unexpected exception") - errors["base"] = "unknown" - else: + if not (errors := await self._async_validate_input(user_input)): # Create Entry return self.async_create_entry( title=( @@ -110,6 +98,54 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN): 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: + """Handle reauthentication confirmation.""" + errors: dict[str, str] = {} + reauth_entry = self._get_reauth_entry() + if user_input is not None and not ( + errors := await self._async_validate_input( + {**reauth_entry.data, **user_input} + ) + ): + return self.async_update_reload_and_abort( + reauth_entry, data_updates=user_input + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=probatio.Schema( + {probatio.Required(probatio.Secret(CONF_API_KEY)): str} + ), + description_placeholders={ + "name": reauth_entry.title, + "api_key_url": _API_KEY_URL, + }, + errors=errors, + ) + + async def _async_validate_input(self, data: dict[str, Any]) -> dict[str, str]: + """Validate the input and return any errors.""" + try: + await validate_input(self.hass, data) + except CannotConnect: + return {"base": "cannot_connect"} + except InvalidAuth: + return {"base": "invalid_auth"} + except InvalidLocation: + return {"base": "invalid_location"} + except Exception: + _LOGGER.exception("Unexpected exception") + return {"base": "unknown"} + return {} + class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect.""" diff --git a/homeassistant/components/airnow/coordinator.py b/homeassistant/components/airnow/coordinator.py index f2a020881b5b..ce5fdcb373fe 100644 --- a/homeassistant/components/airnow/coordinator.py +++ b/homeassistant/components/airnow/coordinator.py @@ -8,10 +8,11 @@ from aiohttp import ClientSession from aiohttp.client_exceptions import ClientConnectorError from pyairnow import WebServiceAPI from pyairnow.conv import aqi_to_concentration -from pyairnow.errors import AirNowError, InvalidJsonError +from pyairnow.errors import AirNowError, InvalidJsonError, InvalidKeyError 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 ( @@ -77,6 +78,10 @@ class AirNowDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): self.longitude, ) + except InvalidKeyError as error: + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from error except (AirNowError, ClientConnectorError, InvalidJsonError) as error: raise UpdateFailed(error) from error diff --git a/homeassistant/components/airnow/quality_scale.yaml b/homeassistant/components/airnow/quality_scale.yaml index a1f1bc22ad95..1c91d10554ee 100644 --- a/homeassistant/components/airnow/quality_scale.yaml +++ b/homeassistant/components/airnow/quality_scale.yaml @@ -41,7 +41,7 @@ rules: integration-owner: todo log-when-unavailable: todo parallel-updates: done - reauthentication-flow: todo + reauthentication-flow: done test-coverage: todo # Gold devices: todo diff --git a/homeassistant/components/airnow/strings.json b/homeassistant/components/airnow/strings.json index ef921a5cd451..b92693080f35 100644 --- a/homeassistant/components/airnow/strings.json +++ b/homeassistant/components/airnow/strings.json @@ -10,6 +10,16 @@ "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::airnow::config::step::user::data_description::api_key%]" + }, + "description": "The API key for {name} is no longer valid. To generate a new API key, go to {api_key_url}.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "user": { "data": { "api_key": "[%key:common::config_flow::data::api_key%]", @@ -38,5 +48,10 @@ } } } + }, + "exceptions": { + "invalid_auth": { + "message": "The AirNow API key is invalid." + } } } diff --git a/tests/components/airnow/test_config_flow.py b/tests/components/airnow/test_config_flow.py index ca7ef7e7f277..c159f4260ab6 100644 --- a/tests/components/airnow/test_config_flow.py +++ b/tests/components/airnow/test_config_flow.py @@ -205,3 +205,59 @@ async def test_config_migration( assert config_entry.version == 3 assert CONF_RADIUS not in config_entry.data assert CONF_RADIUS not in config_entry.options + + +@pytest.mark.usefixtures("setup_airnow") +async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: + """Test reauthentication.""" + result = await config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "new_key"} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert config_entry.data == { + CONF_API_KEY: "new_key", + CONF_LATITUDE: 34.053718, + CONF_LONGITUDE: -118.244842, + } + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + pytest.param(InvalidKeyError, "invalid_auth", id="invalid_auth"), + pytest.param(AirNowError, "cannot_connect", id="cannot_connect"), + pytest.param(EmptyResponseError, "invalid_location", id="invalid_location"), + pytest.param(RuntimeError, "unknown", id="unknown"), + ], +) +@pytest.mark.usefixtures("setup_airnow") +async def test_reauth_errors( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_api_get: AsyncMock, + exception: type[Exception], + error: str, +) -> None: + """Test reauthentication errors and recovery.""" + result = await config_entry.start_reauth_flow(hass) + + mock_api_get.side_effect = exception + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "new_key"} + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + + mock_api_get.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_API_KEY: "new_key"} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert config_entry.data[CONF_API_KEY] == "new_key" diff --git a/tests/components/airnow/test_init.py b/tests/components/airnow/test_init.py new file mode 100644 index 000000000000..035ee32c9f99 --- /dev/null +++ b/tests/components/airnow/test_init.py @@ -0,0 +1,54 @@ +"""Test the AirNow integration setup.""" + +from datetime import timedelta +from unittest.mock import AsyncMock, patch + +from freezegun.api import FrozenDateTimeFactory +from pyairnow.errors import InvalidKeyError +import pytest + +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry, async_fire_time_changed + + +@pytest.mark.parametrize("mock_api_get", [AsyncMock(side_effect=InvalidKeyError)]) +@pytest.mark.usefixtures("setup_airnow") +async def test_setup_auth_failed( + hass: HomeAssistant, config_entry: MockConfigEntry +) -> None: + """Test an invalid API key during setup starts a reauth flow.""" + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert 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"] == config_entry.entry_id + + +async def test_update_auth_failed( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_api_get: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test an invalid API key during a scheduled refresh starts a reauth flow.""" + # Sensor platform is needed so the coordinator has listeners and polls + with patch("pyairnow.WebServiceAPI._get", mock_api_get): + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.LOADED + + mock_api_get.side_effect = InvalidKeyError + freezer.tick(timedelta(minutes=30)) + 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"] == config_entry.entry_id