mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Add reauthentication flow to ElevenLabs (#186206)
Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Erwin Douna <e.douna@gmail.com>
This commit is contained in:
co-authored by
Claude
Erwin Douna
parent
cb75e26c3c
commit
0b6fda052c
@@ -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")
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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%]"
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user