Add reauthentication to azure_storage (#139411)

* Add reauthentication to azure_storage

* update docstring
This commit is contained in:
Josef Zweck 2025-02-27 10:17:57 +01:00 committed by GitHub
parent b505722f38
commit 2150a668b0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 140 additions and 14 deletions

View File

@ -13,7 +13,11 @@ from azure.storage.blob.aio import ContainerClient
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryError,
ConfigEntryNotReady,
)
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .const import (
@ -52,7 +56,7 @@ async def async_setup_entry(
translation_placeholders={CONF_ACCOUNT_NAME: entry.data[CONF_ACCOUNT_NAME]},
) from err
except ClientAuthenticationError as err:
raise ConfigEntryError(
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
translation_placeholders={CONF_ACCOUNT_NAME: entry.data[CONF_ACCOUNT_NAME]},

View File

@ -1,5 +1,6 @@
"""Config flow for Azure Storage integration."""
from collections.abc import Mapping
import logging
from typing import Any
@ -26,6 +27,26 @@ _LOGGER = logging.getLogger(__name__)
class AzureStorageConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for azure storage."""
def get_account_url(self, account_name: str) -> str:
"""Get the account URL."""
return f"https://{account_name}.blob.core.windows.net/"
async def validate_config(
self, container_client: ContainerClient
) -> dict[str, str]:
"""Validate the configuration."""
errors: dict[str, str] = {}
try:
await container_client.exists()
except ResourceNotFoundError:
errors["base"] = "cannot_connect"
except ClientAuthenticationError:
errors[CONF_STORAGE_ACCOUNT_KEY] = "invalid_auth"
except Exception:
_LOGGER.exception("Unknown exception occurred")
errors["base"] = "unknown"
return errors
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
@ -38,20 +59,13 @@ class AzureStorageConfigFlow(ConfigFlow, domain=DOMAIN):
{CONF_ACCOUNT_NAME: user_input[CONF_ACCOUNT_NAME]}
)
container_client = ContainerClient(
account_url=f"https://{user_input[CONF_ACCOUNT_NAME]}.blob.core.windows.net/",
account_url=self.get_account_url(user_input[CONF_ACCOUNT_NAME]),
container_name=user_input[CONF_CONTAINER_NAME],
credential=user_input[CONF_STORAGE_ACCOUNT_KEY],
transport=AioHttpTransport(session=async_get_clientsession(self.hass)),
)
try:
await container_client.exists()
except ResourceNotFoundError:
errors["base"] = "cannot_connect"
except ClientAuthenticationError:
errors[CONF_STORAGE_ACCOUNT_KEY] = "invalid_auth"
except Exception:
_LOGGER.exception("Unknown exception occurred")
errors["base"] = "unknown"
errors = await self.validate_config(container_client)
if not errors:
return self.async_create_entry(
title=f"{user_input[CONF_ACCOUNT_NAME]}/{user_input[CONF_CONTAINER_NAME]}",
@ -70,3 +84,39 @@ class AzureStorageConfigFlow(ConfigFlow, domain=DOMAIN):
),
errors=errors,
)
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:
"""Confirm reauth dialog."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
if user_input is not None:
container_client = ContainerClient(
account_url=self.get_account_url(reauth_entry.data[CONF_ACCOUNT_NAME]),
container_name=reauth_entry.data[CONF_CONTAINER_NAME],
credential=user_input[CONF_STORAGE_ACCOUNT_KEY],
transport=AioHttpTransport(session=async_get_clientsession(self.hass)),
)
errors = await self.validate_config(container_client)
if not errors:
return self.async_update_reload_and_abort(
reauth_entry,
data={**reauth_entry.data, **user_input},
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema(
{
vol.Required(CONF_STORAGE_ACCOUNT_KEY): str,
}
),
errors=errors,
)

View File

@ -57,7 +57,7 @@ rules:
status: exempt
comment: |
This integration does not have platforms.
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done
# Gold

View File

@ -19,10 +19,21 @@
},
"description": "Set up an Azure (Blob) storage account to be used for backups.",
"title": "Add Azure storage account"
},
"reauth_confirm": {
"data": {
"storage_account_key": "[%key:component::azure_storage::config::step::user::data::storage_account_key%]"
},
"data_description": {
"storage_account_key": "[%key:component::azure_storage::config::step::user::data_description::storage_account_key%]"
},
"description": "Provide a new storage account key.",
"title": "Reauthenticate Azure storage account"
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
}
},
"issues": {

View File

@ -15,6 +15,7 @@ from homeassistant.config_entries import SOURCE_USER, ConfigFlowResult
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import setup_integration
from .const import USER_INPUT
from tests.common import MockConfigEntry
@ -111,3 +112,63 @@ async def test_abort_if_already_configured(
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the reauth flow works."""
await setup_integration(hass, mock_config_entry)
result = await mock_config_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_STORAGE_ACCOUNT_KEY: "new_key"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {
**USER_INPUT,
CONF_STORAGE_ACCOUNT_KEY: "new_key",
}
async def test_reauth_flow_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the reauth flow works with an errors."""
await setup_integration(hass, mock_config_entry)
mock_client.exists.side_effect = Exception()
result = await mock_config_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_STORAGE_ACCOUNT_KEY: "new_key"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "unknown"}
# fix the error and finish the flow successfully
mock_client.exists.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_STORAGE_ACCOUNT_KEY: "new_key"}
)
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {
**USER_INPUT,
CONF_STORAGE_ACCOUNT_KEY: "new_key",
}