From cbcfc43c5a75a153dd13ebdb2c532da7c29ad14c Mon Sep 17 00:00:00 2001 From: Denis Shulyaka Date: Sat, 14 Feb 2026 23:53:25 +0300 Subject: [PATCH] Add reauthentication to Anthropic (#163019) --- .../components/anthropic/__init__.py | 5 +-- .../components/anthropic/config_flow.py | 22 +++++++++++ .../components/anthropic/strings.json | 12 +++++- .../components/anthropic/test_config_flow.py | 38 +++++++++++++++++++ tests/components/anthropic/test_init.py | 38 +++++++++++++------ 5 files changed, 99 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/anthropic/__init__.py b/homeassistant/components/anthropic/__init__.py index 9c01a9205ad..4f5643c30d1 100644 --- a/homeassistant/components/anthropic/__init__.py +++ b/homeassistant/components/anthropic/__init__.py @@ -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 diff --git a/homeassistant/components/anthropic/config_flow.py b/homeassistant/components/anthropic/config_flow.py index d1fc39380f7..ddd75795cfa 100644 --- a/homeassistant/components/anthropic/config_flow.py +++ b/homeassistant/components/anthropic/config_flow.py @@ -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( diff --git a/homeassistant/components/anthropic/strings.json b/homeassistant/components/anthropic/strings.json index 8514c8f97b9..21c67d5d6fb 100644 --- a/homeassistant/components/anthropic/strings.json +++ b/homeassistant/components/anthropic/strings.json @@ -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%]" diff --git a/tests/components/anthropic/test_config_flow.py b/tests/components/anthropic/test_config_flow.py index 50ac427e0d4..8e56dac3325 100644 --- a/tests/components/anthropic/test_config_flow.py +++ b/tests/components/anthropic/test_config_flow.py @@ -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"), [ diff --git a/tests/components/anthropic/test_init.py b/tests/components/anthropic/test_init.py index 89f8a6355b9..6ace55c6e5f 100644 --- a/tests/components/anthropic/test_init.py +++ b/tests/components/anthropic/test_init.py @@ -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,