1
0
mirror of https://github.com/home-assistant/core.git synced 2026-02-14 23:28:42 +00:00

Add reauthentication to Anthropic (#163019)

This commit is contained in:
Denis Shulyaka
2026-02-14 23:53:25 +03:00
committed by GitHub
parent acaa2aeeee
commit cbcfc43c5a
5 changed files with 99 additions and 16 deletions

View File

@@ -7,7 +7,7 @@ import anthropic
from homeassistant.config_entries import ConfigEntry, ConfigSubentry
from homeassistant.const import CONF_API_KEY, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
@@ -47,8 +47,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: AnthropicConfigEntry) ->
try:
await client.models.list(timeout=10.0)
except anthropic.AuthenticationError as err:
LOGGER.error("Invalid API key: %s", err)
return False
raise ConfigEntryAuthFailed(err) from err
except anthropic.AnthropicError as err:
raise ConfigEntryNotReady(err) from err

View File

@@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Mapping
import json
import logging
import re
@@ -13,6 +14,7 @@ from voluptuous_openapi import convert
from homeassistant.components.zone import ENTITY_ID_HOME
from homeassistant.config_entries import (
SOURCE_REAUTH,
ConfigEntryState,
ConfigFlow,
ConfigFlowResult,
@@ -164,6 +166,10 @@ class AnthropicConfigFlow(ConfigFlow, domain=DOMAIN):
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if self.source == SOURCE_REAUTH:
return self.async_update_reload_and_abort(
self._get_reauth_entry(), data_updates=user_input
)
return self.async_create_entry(
title="Claude",
data=user_input,
@@ -192,6 +198,22 @@ class AnthropicConfigFlow(ConfigFlow, domain=DOMAIN):
},
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Dialog that informs the user that reauth is required."""
if not user_input:
return self.async_show_form(
step_id="reauth_confirm", data_schema=STEP_USER_DATA_SCHEMA
)
return await self.async_step_user(user_input)
@classmethod
@callback
def async_get_supported_subentry_types(

View File

@@ -1,7 +1,8 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
},
"error": {
"authentication_error": "[%key:common::config_flow::error::invalid_auth%]",
@@ -10,6 +11,15 @@
"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::anthropic::config::step::user::data_description::api_key%]"
},
"description": "Reauthentication required. Please enter your updated API key."
},
"user": {
"data": {
"api_key": "[%key:common::config_flow::data::api_key%]"

View File

@@ -780,6 +780,44 @@ async def test_creating_ai_task_subentry_advanced(
}
async def test_reauth(hass: HomeAssistant) -> None:
"""Test we can reauthenticate."""
# Pretend we already set up a config entry.
hass.config.components.add("anthropic")
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
state=config_entries.ConfigEntryState.LOADED,
)
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"
with (
patch(
"homeassistant.components.anthropic.config_flow.anthropic.resources.models.AsyncModels.list",
new_callable=AsyncMock,
),
patch(
"homeassistant.components.anthropic.async_setup_entry",
return_value=True,
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_API_KEY: "new_api_key",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
@pytest.mark.parametrize(
("current_llm_apis", "suggested_llm_apis", "expected_options"),
[

View File

@@ -9,11 +9,16 @@ from anthropic import (
AuthenticationError,
BadRequestError,
)
import httpx
from httpx import URL, Request, Response
import pytest
from homeassistant.components.anthropic.const import DATA_REPAIR_DEFER_RELOAD, DOMAIN
from homeassistant.config_entries import ConfigEntryDisabler, ConfigSubentryData
from homeassistant.config_entries import (
ConfigEntryDisabler,
ConfigEntryState,
ConfigSubentryData,
)
from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er, llm
@@ -40,17 +45,6 @@ from tests.common import MockConfigEntry
),
"anthropic integration not ready yet: Your credit balance is too low to access the Claude API",
),
(
AuthenticationError(
message="invalid x-api-key",
response=Response(
status_code=401,
request=Request(method="POST", url=URL()),
),
body={"type": "error", "error": {"type": "authentication_error"}},
),
"Invalid API key",
),
],
)
async def test_init_error(
@@ -70,6 +64,26 @@ async def test_init_error(
assert error in caplog.text
async def test_init_auth_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test auth error during init errors."""
with patch(
"anthropic.resources.models.AsyncModels.list",
side_effect=AuthenticationError(
response=httpx.Response(
status_code=500, request=httpx.Request(method="GET", url="test")
),
body=None,
message="",
),
):
assert await async_setup_component(hass, "anthropic", {})
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_deferred_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,