Fix here_travel_time reauthentication (#195758)

This commit is contained in:
Kevin Stillhammer
2026-12-01 11:14:53 +01:00
committed by GitHub
parent d0252834e2
commit e5cb19977a
4 changed files with 131 additions and 15 deletions
@@ -63,16 +63,23 @@ DEFAULT_OPTIONS = {
}
async def async_validate_api_key(api_key: str) -> None:
async def async_validate_api_key(api_key: str) -> dict[str, str]:
"""Validate the user input allows us to connect."""
known_working_origin = Place(latitude=38.9, longitude=-77.04833)
known_working_destination = Place(latitude=39.0, longitude=-77.1)
await HERERoutingApi(api_key).route(
origin=known_working_origin,
destination=known_working_destination,
transport_mode=TransportMode.CAR,
)
try:
await HERERoutingApi(api_key).route(
origin=known_working_origin,
destination=known_working_destination,
transport_mode=TransportMode.CAR,
)
except HERERoutingUnauthorizedError:
return {"base": "invalid_auth"}
except HERERoutingError, HERETransitError:
_LOGGER.exception("Unexpected exception")
return {"base": "unknown"}
return {}
def get_user_step_schema(data: Mapping[str, Any]) -> probatio.Schema:
@@ -119,13 +126,7 @@ class HERETravelTimeConfigFlow(ConfigFlow, domain=DOMAIN):
errors = {}
user_input = user_input or {}
if user_input:
try:
await async_validate_api_key(user_input[CONF_API_KEY])
except HERERoutingUnauthorizedError:
errors["base"] = "invalid_auth"
except HERERoutingError, HERETransitError:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
errors = await async_validate_api_key(user_input[CONF_API_KEY])
if not errors:
self._config[CONF_API_KEY] = user_input[CONF_API_KEY]
self._config[CONF_MODE] = user_input[CONF_MODE]
@@ -134,6 +135,31 @@ class HERETravelTimeConfigFlow(ConfigFlow, domain=DOMAIN):
step_id="user", data_schema=get_user_step_schema(user_input), errors=errors
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Start reauthentication when HERE rejects the API key."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Validate and save a replacement API key."""
errors: dict[str, str] = {}
if user_input is not None:
errors = await async_validate_api_key(user_input[CONF_API_KEY])
if not errors:
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=probatio.Schema({probatio.Required(CONF_API_KEY): cv.string}),
errors=errors,
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
@@ -8,6 +8,7 @@ import here_routing
from here_routing import (
HERERoutingApi,
HERERoutingTooManyRequestsError,
HERERoutingUnauthorizedError,
Return,
RoutingMode,
Spans,
@@ -21,12 +22,14 @@ from here_transit import (
HERETransitDepartureArrivalTooCloseError,
HERETransitNoRouteFoundError,
HERETransitTooManyRequestsError,
HERETransitUnauthorizedError,
)
import probatio
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_MODE, UnitOfLength
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.location import find_coordinates
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@@ -115,6 +118,10 @@ class HERERoutingDataUpdateCoordinator(DataUpdateCoordinator[HERETravelTimeData]
return_values=[Return.POLYINE, Return.SUMMARY],
spans=[Spans.NAMES],
)
except HERERoutingUnauthorizedError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="invalid_auth"
) from error
except HERERoutingTooManyRequestsError as error:
assert self.update_interval is not None
_LOGGER.debug(
@@ -235,6 +242,10 @@ class HERETransitDataUpdateCoordinator(
here_transit.Return.TRAVEL_SUMMARY,
],
)
except HERETransitUnauthorizedError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="invalid_auth"
) from error
except HERETransitTooManyRequestsError as error:
assert self.update_interval is not None
_LOGGER.debug(
@@ -46,6 +46,12 @@
},
"title": "Choose origin"
},
"reauth_confirm": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"
},
"description": "HERE rejected the current API key. Enter a valid API key to resume updates."
},
"user": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]",
@@ -67,6 +73,11 @@
}
}
},
"exceptions": {
"invalid_auth": {
"message": "[%key:common::config_flow::error::invalid_auth%]"
}
},
"issues": {
"multiple_here_travel_time_entries": {
"description": "HERE deprecated the previous free tier. The new Base Plan has only 5000 instead of the previous 30000 free requests per month.\n\nSince you have more than one HERE Travel Time integration configured, you will need to disable or remove the additional integrations to avoid exceeding the free request limit.\nYou can ignore this issue if you are okay with the additional cost.",
@@ -8,6 +8,7 @@ from freezegun.api import FrozenDateTimeFactory
from here_routing import (
HERERoutingError,
HERERoutingTooManyRequestsError,
HERERoutingUnauthorizedError,
Place,
Return,
RoutingMode,
@@ -20,6 +21,7 @@ from here_transit import (
HERETransitNoRouteFoundError,
HERETransitNoTransitRouteFoundError,
HERETransitTooManyRequestsError,
HERETransitUnauthorizedError,
)
import pytest
from pytest_homeassistant.common import (
@@ -60,6 +62,7 @@ from homeassistant.components.sensor import (
ATTR_STATE_CLASS,
SensorStateClass,
)
from homeassistant.config_entries import SOURCE_REAUTH
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_ICON,
@@ -73,6 +76,7 @@ from homeassistant.const import (
UnitOfTime,
)
from homeassistant.core import CoreState, HomeAssistant, State
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.setup import async_setup_component
from .conftest import RESPONSE, TRANSIT_RESPONSE
@@ -92,8 +96,8 @@ async def _setup_and_start(
data: Mapping[str, object] | None = None,
options: Mapping[str, object] | None = None,
already_started: bool = False,
) -> None:
"""Set up the entry before or after Home Assistant startup."""
) -> MockConfigEntry:
"""Set up and return the entry before or after Home Assistant startup."""
hass.set_state(CoreState.running if already_started else CoreState.not_running)
entry = MockConfigEntry(
domain=DOMAIN,
@@ -111,6 +115,7 @@ async def _setup_and_start(
hass.set_state(CoreState.running)
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
return entry
@pytest.mark.parametrize(
@@ -453,6 +458,69 @@ async def test_restored_reading_unavailable_after_failed_refresh(
assert state.state == "unavailable"
@pytest.mark.usefixtures("valid_response")
@pytest.mark.parametrize(
("mode", "route_method", "error"),
[
pytest.param(
TRAVEL_MODE_CAR,
"here_routing.HERERoutingApi.route",
HERERoutingUnauthorizedError,
id="routing",
),
pytest.param(
TRAVEL_MODE_PUBLIC,
"here_transit.HERETransitApi.route",
HERETransitUnauthorizedError,
id="transit",
),
],
)
async def test_expired_api_key(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mode: str,
route_method: str,
error: type[Exception],
) -> None:
"""Test reauthentication after the API rejects a previously valid key."""
entry_data = {**DEFAULT_CONFIG, CONF_MODE: mode}
entry = await _setup_and_start(
hass,
data=entry_data,
already_started=True,
)
with patch(route_method, side_effect=error("Invalid API key")):
freezer.tick(timedelta(seconds=DEFAULT_SCAN_INTERVAL + 1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
(flow,) = entry.async_get_active_flows(hass, {SOURCE_REAUTH})
assert flow["step_id"] == "reauth_confirm"
# First verify that reauthentication rejects an invalid replacement key.
with patch(
"here_routing.HERERoutingApi.route",
side_effect=HERERoutingUnauthorizedError("Invalid API key"),
):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"], {CONF_API_KEY: "invalid-key"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_auth"}
assert entry.data == entry_data
result = await hass.config_entries.flow.async_configure(
flow["flow_id"], {CONF_API_KEY: "replacement-key"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert entry.data == {**entry_data, CONF_API_KEY: "replacement-key"}
@pytest.mark.usefixtures("valid_response")
async def test_restore_state(hass: HomeAssistant) -> None:
"""Test sensor restore state."""