Skip to content

Commit cbcfc43

Browse files
authored
Add reauthentication to Anthropic (home-assistant#163019)
1 parent acaa2ae commit cbcfc43

5 files changed

Lines changed: 99 additions & 16 deletions

File tree

homeassistant/components/anthropic/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from homeassistant.config_entries import ConfigEntry, ConfigSubentry
88
from homeassistant.const import CONF_API_KEY, Platform
99
from homeassistant.core import HomeAssistant
10-
from homeassistant.exceptions import ConfigEntryNotReady
10+
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
1111
from homeassistant.helpers import (
1212
config_validation as cv,
1313
device_registry as dr,
@@ -47,8 +47,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: AnthropicConfigEntry) ->
4747
try:
4848
await client.models.list(timeout=10.0)
4949
except anthropic.AuthenticationError as err:
50-
LOGGER.error("Invalid API key: %s", err)
51-
return False
50+
raise ConfigEntryAuthFailed(err) from err
5251
except anthropic.AnthropicError as err:
5352
raise ConfigEntryNotReady(err) from err
5453

homeassistant/components/anthropic/config_flow.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
from collections.abc import Mapping
56
import json
67
import logging
78
import re
@@ -13,6 +14,7 @@
1314

1415
from homeassistant.components.zone import ENTITY_ID_HOME
1516
from homeassistant.config_entries import (
17+
SOURCE_REAUTH,
1618
ConfigEntryState,
1719
ConfigFlow,
1820
ConfigFlowResult,
@@ -164,6 +166,10 @@ async def async_step_user(
164166
_LOGGER.exception("Unexpected exception")
165167
errors["base"] = "unknown"
166168
else:
169+
if self.source == SOURCE_REAUTH:
170+
return self.async_update_reload_and_abort(
171+
self._get_reauth_entry(), data_updates=user_input
172+
)
167173
return self.async_create_entry(
168174
title="Claude",
169175
data=user_input,
@@ -192,6 +198,22 @@ async def async_step_user(
192198
},
193199
)
194200

201+
async def async_step_reauth(
202+
self, entry_data: Mapping[str, Any]
203+
) -> ConfigFlowResult:
204+
"""Perform reauth upon an API authentication error."""
205+
return await self.async_step_reauth_confirm()
206+
207+
async def async_step_reauth_confirm(
208+
self, user_input: dict[str, Any] | None = None
209+
) -> ConfigFlowResult:
210+
"""Dialog that informs the user that reauth is required."""
211+
if not user_input:
212+
return self.async_show_form(
213+
step_id="reauth_confirm", data_schema=STEP_USER_DATA_SCHEMA
214+
)
215+
return await self.async_step_user(user_input)
216+
195217
@classmethod
196218
@callback
197219
def async_get_supported_subentry_types(

homeassistant/components/anthropic/strings.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{
22
"config": {
33
"abort": {
4-
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
4+
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
5+
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
56
},
67
"error": {
78
"authentication_error": "[%key:common::config_flow::error::invalid_auth%]",
@@ -10,6 +11,15 @@
1011
"unknown": "[%key:common::config_flow::error::unknown%]"
1112
},
1213
"step": {
14+
"reauth_confirm": {
15+
"data": {
16+
"api_key": "[%key:common::config_flow::data::api_key%]"
17+
},
18+
"data_description": {
19+
"api_key": "[%key:component::anthropic::config::step::user::data_description::api_key%]"
20+
},
21+
"description": "Reauthentication required. Please enter your updated API key."
22+
},
1323
"user": {
1424
"data": {
1525
"api_key": "[%key:common::config_flow::data::api_key%]"

tests/components/anthropic/test_config_flow.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,44 @@ async def test_creating_ai_task_subentry_advanced(
780780
}
781781

782782

783+
async def test_reauth(hass: HomeAssistant) -> None:
784+
"""Test we can reauthenticate."""
785+
# Pretend we already set up a config entry.
786+
hass.config.components.add("anthropic")
787+
mock_config_entry = MockConfigEntry(
788+
domain=DOMAIN,
789+
state=config_entries.ConfigEntryState.LOADED,
790+
)
791+
792+
mock_config_entry.add_to_hass(hass)
793+
result = await mock_config_entry.start_reauth_flow(hass)
794+
795+
assert result["type"] is FlowResultType.FORM
796+
assert result["step_id"] == "reauth_confirm"
797+
798+
with (
799+
patch(
800+
"homeassistant.components.anthropic.config_flow.anthropic.resources.models.AsyncModels.list",
801+
new_callable=AsyncMock,
802+
),
803+
patch(
804+
"homeassistant.components.anthropic.async_setup_entry",
805+
return_value=True,
806+
),
807+
):
808+
result = await hass.config_entries.flow.async_configure(
809+
result["flow_id"],
810+
{
811+
CONF_API_KEY: "new_api_key",
812+
},
813+
)
814+
await hass.async_block_till_done()
815+
816+
assert result["type"] is FlowResultType.ABORT
817+
assert result["reason"] == "reauth_successful"
818+
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
819+
820+
783821
@pytest.mark.parametrize(
784822
("current_llm_apis", "suggested_llm_apis", "expected_options"),
785823
[

tests/components/anthropic/test_init.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,16 @@
99
AuthenticationError,
1010
BadRequestError,
1111
)
12+
import httpx
1213
from httpx import URL, Request, Response
1314
import pytest
1415

1516
from homeassistant.components.anthropic.const import DATA_REPAIR_DEFER_RELOAD, DOMAIN
16-
from homeassistant.config_entries import ConfigEntryDisabler, ConfigSubentryData
17+
from homeassistant.config_entries import (
18+
ConfigEntryDisabler,
19+
ConfigEntryState,
20+
ConfigSubentryData,
21+
)
1722
from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API
1823
from homeassistant.core import HomeAssistant
1924
from homeassistant.helpers import device_registry as dr, entity_registry as er, llm
@@ -40,17 +45,6 @@
4045
),
4146
"anthropic integration not ready yet: Your credit balance is too low to access the Claude API",
4247
),
43-
(
44-
AuthenticationError(
45-
message="invalid x-api-key",
46-
response=Response(
47-
status_code=401,
48-
request=Request(method="POST", url=URL()),
49-
),
50-
body={"type": "error", "error": {"type": "authentication_error"}},
51-
),
52-
"Invalid API key",
53-
),
5448
],
5549
)
5650
async def test_init_error(
@@ -70,6 +64,26 @@ async def test_init_error(
7064
assert error in caplog.text
7165

7266

67+
async def test_init_auth_error(
68+
hass: HomeAssistant,
69+
mock_config_entry: MockConfigEntry,
70+
) -> None:
71+
"""Test auth error during init errors."""
72+
with patch(
73+
"anthropic.resources.models.AsyncModels.list",
74+
side_effect=AuthenticationError(
75+
response=httpx.Response(
76+
status_code=500, request=httpx.Request(method="GET", url="test")
77+
),
78+
body=None,
79+
message="",
80+
),
81+
):
82+
assert await async_setup_component(hass, "anthropic", {})
83+
await hass.async_block_till_done()
84+
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
85+
86+
7387
async def test_deferred_update(
7488
hass: HomeAssistant,
7589
mock_config_entry: MockConfigEntry,

0 commit comments

Comments
 (0)