diff --git a/homeassistant/components/elevenlabs/__init__.py b/homeassistant/components/elevenlabs/__init__.py index 94ec1c3042a4..2b49aec03b4c 100644 --- a/homeassistant/components/elevenlabs/__init__.py +++ b/homeassistant/components/elevenlabs/__init__.py @@ -1,6 +1,7 @@ """The ElevenLabs text-to-speech integration.""" from dataclasses import dataclass +from http import HTTPStatus import logging from elevenlabs import AsyncElevenLabs, Model @@ -27,6 +28,18 @@ PLATFORMS: list[Platform] = [ ] +def _is_invalid_api_key(err: ApiError) -> bool: + """Return whether the API rejected the API key.""" + if err.status_code == HTTPStatus.UNAUTHORIZED: + return True + body = err.body + return ( + isinstance(body, dict) + and isinstance(detail := body.get("detail"), dict) + and detail.get("status") == "invalid_api_key" + ) + + async def get_model_by_id(client: AsyncElevenLabs, model_id: str) -> Model | None: """Get ElevenLabs model from their API by the model_id.""" models = await client.models.list() @@ -62,7 +75,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ElevenLabsConfigEntry) - except ConnectError as err: raise ConfigEntryNotReady("Failed to connect") from err except ApiError as err: - raise ConfigEntryAuthFailed("Auth failed") from err + if _is_invalid_api_key(err): + raise ConfigEntryAuthFailed("Auth failed") from err + raise ConfigEntryNotReady("Failed to fetch models") from err if model is None or (not model.languages): raise ConfigEntryError("Model could not be resolved") diff --git a/homeassistant/components/elevenlabs/config_flow.py b/homeassistant/components/elevenlabs/config_flow.py index 5edb2935f283..d29f7c9fb0f7 100644 --- a/homeassistant/components/elevenlabs/config_flow.py +++ b/homeassistant/components/elevenlabs/config_flow.py @@ -1,10 +1,12 @@ """Config flow for ElevenLabs text-to-speech integration.""" +from collections.abc import Mapping import logging from typing import Any, override from elevenlabs import AsyncElevenLabs from elevenlabs.core import ApiError +from httpx2 import ConnectError import probatio from homeassistant.config_entries import ConfigFlow, ConfigFlowResult, OptionsFlow @@ -74,6 +76,24 @@ class ElevenLabsConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = 1 MINOR_VERSION = 2 + async def _validate_api_key( + self, api_key: str + ) -> tuple[dict[str, str], dict[str, str]]: + """Validate the API key and return the available voices and errors.""" + errors: dict[str, str] = {} + try: + voices, _ = await get_voices_models(self.hass, api_key) + except ConnectError: + errors["base"] = "cannot_connect" + return {}, errors + except ApiError as exc: + errors["base"] = "unknown" + details = getattr(exc, "body", {}).get("detail", {}) + if details.get("status") == "invalid_api_key": + errors["base"] = "invalid_api_key" + return {}, errors + return voices, errors + @override async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -81,16 +101,8 @@ class ElevenLabsConfigFlow(ConfigFlow, domain=DOMAIN): """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: - try: - voices, _ = await get_voices_models(self.hass, user_input[CONF_API_KEY]) - except ApiError as exc: - errors["base"] = "unknown" - details = getattr(exc, "body", {}).get("detail", {}) - if details: - status = details.get("status") - if status == "invalid_api_key": - errors["base"] = "invalid_api_key" - else: + voices, errors = await self._validate_api_key(user_input[CONF_API_KEY]) + if not errors: return self.async_create_entry( title="ElevenLabs", data=user_input, @@ -105,6 +117,28 @@ class ElevenLabsConfigFlow(ConfigFlow, domain=DOMAIN): step_id="user", data_schema=USER_STEP_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: + _, errors = await self._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=USER_STEP_SCHEMA, errors=errors + ) + @staticmethod @override def async_get_options_flow( diff --git a/homeassistant/components/elevenlabs/quality_scale.yaml b/homeassistant/components/elevenlabs/quality_scale.yaml index 439606a57458..087b444b5853 100644 --- a/homeassistant/components/elevenlabs/quality_scale.yaml +++ b/homeassistant/components/elevenlabs/quality_scale.yaml @@ -38,7 +38,7 @@ rules: comment: > There is no state in the TTS platform and we can't check poll if the TTS service is available. action-exceptions: done - reauthentication-flow: todo + reauthentication-flow: done parallel-updates: done test-coverage: todo integration-owner: done diff --git a/homeassistant/components/elevenlabs/strings.json b/homeassistant/components/elevenlabs/strings.json index 800d1fec02c6..918d065cc30a 100644 --- a/homeassistant/components/elevenlabs/strings.json +++ b/homeassistant/components/elevenlabs/strings.json @@ -1,10 +1,21 @@ { "config": { "error": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "invalid_api_key": "[%key:common::config_flow::error::invalid_api_key%]", "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::elevenlabs::config::step::user::data_description::api_key%]" + }, + "description": "The ElevenLabs API key is no longer valid. Please enter a new API key.", + "title": "[%key:common::config_flow::title::reauth%]" + }, "user": { "data": { "api_key": "[%key:common::config_flow::data::api_key%]" diff --git a/tests/components/elevenlabs/test_config_flow.py b/tests/components/elevenlabs/test_config_flow.py index 559a18621a92..04a3f1d6556d 100644 --- a/tests/components/elevenlabs/test_config_flow.py +++ b/tests/components/elevenlabs/test_config_flow.py @@ -62,13 +62,26 @@ async def test_user_step( mock_setup_entry.assert_called_once() -async def test_invalid_api_key( +@pytest.mark.parametrize( + ("client_fixture", "error"), + [ + pytest.param( + "mock_async_client_api_error", "invalid_api_key", id="invalid_api_key" + ), + pytest.param( + "mock_async_client_connect_error", "cannot_connect", id="cannot_connect" + ), + ], +) +async def test_user_step_errors( hass: HomeAssistant, mock_setup_entry: AsyncMock, - mock_async_client_api_error: AsyncMock, request: pytest.FixtureRequest, + client_fixture: str, + error: str, ) -> None: - """Test user step with invalid api key.""" + """Test user step errors and recovery.""" + request.getfixturevalue(client_fixture) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} @@ -83,7 +96,7 @@ async def test_invalid_api_key( }, ) assert result["type"] is FlowResultType.FORM - assert result["errors"] == {"base": "invalid_api_key"} + assert result["errors"] == {"base": error} mock_setup_entry.assert_not_called() @@ -288,3 +301,69 @@ async def test_options_flow_voice_settings_default( CONF_STYLE: DEFAULT_STYLE, CONF_USE_SPEAKER_BOOST: DEFAULT_USE_SPEAKER_BOOST, } + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_async_client") +async def test_reauth_flow( + hass: HomeAssistant, + mock_entry: MockConfigEntry, +) -> None: + """Test reauthentication flow.""" + mock_entry.add_to_hass(hass) + + result = await mock_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_entry.data == {CONF_API_KEY: "new_api_key"} + + +@pytest.mark.parametrize( + ("client_fixture", "error"), + [ + pytest.param( + "mock_async_client_api_error", "invalid_api_key", id="invalid_api_key" + ), + pytest.param("mock_async_client_voices_error", "unknown", id="unknown"), + pytest.param( + "mock_async_client_connect_error", "cannot_connect", id="cannot_connect" + ), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_flow_errors( + hass: HomeAssistant, + mock_entry: MockConfigEntry, + request: pytest.FixtureRequest, + client_fixture: str, + error: str, +) -> None: + """Test reauthentication flow errors and recovery.""" + mock_entry.add_to_hass(hass) + request.getfixturevalue(client_fixture) + + result = await mock_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["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": error} + + request.getfixturevalue("mock_async_client") + + 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_entry.data == {CONF_API_KEY: "new_api_key"} diff --git a/tests/components/elevenlabs/test_setup.py b/tests/components/elevenlabs/test_setup.py index 5ff85fae7e01..fd12a9ded9e6 100644 --- a/tests/components/elevenlabs/test_setup.py +++ b/tests/components/elevenlabs/test_setup.py @@ -2,8 +2,11 @@ from unittest.mock import MagicMock +from elevenlabs.core import ApiError +import pytest + from homeassistant.components.elevenlabs.const import CONF_VOICE -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry @@ -35,6 +38,53 @@ async def test_setup_connect_error( assert mock_entry.state is ConfigEntryState.SETUP_RETRY +@pytest.mark.parametrize( + "error", + [ + pytest.param(ApiError(status_code=401), id="unauthorized"), + pytest.param( + ApiError( + status_code=400, + body={"detail": {"status": "invalid_api_key", "message": "Invalid"}}, + ), + id="invalid_api_key", + ), + ], +) +async def test_setup_auth_error_starts_reauth( + hass: HomeAssistant, + mock_async_client: MagicMock, + mock_entry: MockConfigEntry, + error: ApiError, +) -> None: + """Test an invalid API key during setup starts a reauth flow.""" + mock_async_client.return_value.models.list.side_effect = error + mock_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_entry.entry_id) + + assert mock_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_entry.entry_id + + +async def test_setup_api_error_retries( + hass: HomeAssistant, + mock_async_client: MagicMock, + mock_entry: MockConfigEntry, +) -> None: + """Test a non-authentication API error during setup retries setup.""" + mock_async_client.return_value.models.list.side_effect = ApiError( + status_code=500, body="Internal Server Error" + ) + mock_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_entry.entry_id) + + assert mock_entry.state is ConfigEntryState.SETUP_RETRY + assert not hass.config_entries.flow.async_progress() + + async def test_options_update_reloads_once( hass: HomeAssistant, mock_async_client: MagicMock,