mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
Add OAuth client credentials support to Tailscale (#176874)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
8ec47971e2
commit
18a0a43ace
@@ -2,7 +2,9 @@
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
|
||||
from .const import CONF_OAUTH_CLIENT_ID
|
||||
from .coordinator import TailscaleConfigEntry, TailscaleDataUpdateCoordinator
|
||||
|
||||
PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
|
||||
@@ -10,7 +12,20 @@ PLATFORMS = [Platform.BINARY_SENSOR, Platform.SENSOR]
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: TailscaleConfigEntry) -> bool:
|
||||
"""Set up Tailscale from a config entry."""
|
||||
if CONF_OAUTH_CLIENT_ID not in entry.data:
|
||||
# Entries created with a 90-day API access token migrate to a
|
||||
# non-expiring OAuth client through reauthentication.
|
||||
raise ConfigEntryAuthFailed(
|
||||
"Tailscale now authenticates with an OAuth client instead of an "
|
||||
"API access token"
|
||||
)
|
||||
|
||||
coordinator = TailscaleDataUpdateCoordinator(hass, entry)
|
||||
|
||||
# Registered before the first refresh: a failed setup does not call
|
||||
# async_unload_entry, but does run on_unload callbacks.
|
||||
entry.async_on_unload(coordinator.tailscale.close)
|
||||
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
entry.runtime_data = coordinator
|
||||
|
||||
@@ -7,24 +7,42 @@ import probatio
|
||||
from tailscale import Tailscale, TailscaleAuthenticationError, TailscaleError
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from .const import CONF_TAILNET, DOMAIN
|
||||
from .const import CONF_OAUTH_CLIENT_ID, CONF_OAUTH_CLIENT_SECRET, CONF_TAILNET, DOMAIN
|
||||
|
||||
AUTHKEYS_URL = "https://login.tailscale.com/admin/settings/keys"
|
||||
OAUTH_URL = "https://login.tailscale.com/admin/settings/oauth"
|
||||
|
||||
OAUTH_SCHEMA = {
|
||||
probatio.Required(CONF_OAUTH_CLIENT_ID): str,
|
||||
probatio.Required(probatio.Secret(CONF_OAUTH_CLIENT_SECRET)): str,
|
||||
}
|
||||
|
||||
STEP_USER_SCHEMA = probatio.Schema(
|
||||
{probatio.Required(CONF_TAILNET): str, **OAUTH_SCHEMA}
|
||||
)
|
||||
|
||||
STEP_REAUTH_SCHEMA = probatio.Schema(OAUTH_SCHEMA)
|
||||
|
||||
|
||||
async def validate_input(hass: HomeAssistant, *, tailnet: str, api_key: str) -> None:
|
||||
"""Try using the give tailnet & api key against the Tailscale API."""
|
||||
async def validate_input(
|
||||
hass: HomeAssistant, *, tailnet: str, user_input: Mapping[str, Any]
|
||||
) -> None:
|
||||
"""Try using the given tailnet & OAuth credentials against the Tailscale API."""
|
||||
session = async_get_clientsession(hass)
|
||||
tailscale = Tailscale(
|
||||
session=session,
|
||||
api_key=api_key,
|
||||
tailnet=tailnet,
|
||||
oauth_client_id=user_input[CONF_OAUTH_CLIENT_ID],
|
||||
oauth_client_secret=user_input[CONF_OAUTH_CLIENT_SECRET],
|
||||
)
|
||||
await tailscale.devices()
|
||||
try:
|
||||
await tailscale.devices()
|
||||
finally:
|
||||
# Requesting an access token schedules a task that expires it; closing
|
||||
# cancels it. The session is owned by Home Assistant and left open.
|
||||
await tailscale.close()
|
||||
|
||||
|
||||
class TailscaleFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
@@ -40,43 +58,28 @@ class TailscaleFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
errors = {}
|
||||
|
||||
if user_input is not None:
|
||||
await self.async_set_unique_id(user_input[CONF_TAILNET])
|
||||
self._abort_if_unique_id_configured()
|
||||
try:
|
||||
await validate_input(
|
||||
self.hass,
|
||||
tailnet=user_input[CONF_TAILNET],
|
||||
api_key=user_input[CONF_API_KEY],
|
||||
user_input=user_input,
|
||||
)
|
||||
except TailscaleAuthenticationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except TailscaleError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(user_input[CONF_TAILNET])
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title=user_input[CONF_TAILNET],
|
||||
data={
|
||||
CONF_TAILNET: user_input[CONF_TAILNET],
|
||||
CONF_API_KEY: user_input[CONF_API_KEY],
|
||||
},
|
||||
data=user_input,
|
||||
)
|
||||
else:
|
||||
user_input = {}
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
description_placeholders={"authkeys_url": AUTHKEYS_URL},
|
||||
data_schema=probatio.Schema(
|
||||
{
|
||||
probatio.Required(
|
||||
CONF_TAILNET, default=user_input.get(CONF_TAILNET, "")
|
||||
): str,
|
||||
probatio.Required(
|
||||
probatio.Secret(CONF_API_KEY),
|
||||
default=user_input.get(CONF_API_KEY, ""),
|
||||
): str,
|
||||
}
|
||||
),
|
||||
data_schema=STEP_USER_SCHEMA,
|
||||
description_placeholders={"oauth_url": OAUTH_URL},
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@@ -89,32 +92,32 @@ class TailscaleFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
async def async_step_reauth_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle re-authentication with Tailscale."""
|
||||
"""Re-authenticate with an OAuth client, migrating an API token entry."""
|
||||
errors = {}
|
||||
reauth_entry = self._get_reauth_entry()
|
||||
|
||||
if user_input is not None:
|
||||
reauth_entry = self._get_reauth_entry()
|
||||
try:
|
||||
await validate_input(
|
||||
self.hass,
|
||||
tailnet=reauth_entry.data[CONF_TAILNET],
|
||||
api_key=user_input[CONF_API_KEY],
|
||||
user_input=user_input,
|
||||
)
|
||||
except TailscaleAuthenticationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except TailscaleError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
# Replace, rather than update, so a migrated entry's API access
|
||||
# token is not left behind in storage.
|
||||
return self.async_update_reload_and_abort(
|
||||
reauth_entry,
|
||||
data_updates={CONF_API_KEY: user_input[CONF_API_KEY]},
|
||||
data={CONF_TAILNET: reauth_entry.data[CONF_TAILNET], **user_input},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
description_placeholders={"authkeys_url": AUTHKEYS_URL},
|
||||
data_schema=probatio.Schema(
|
||||
{probatio.Required(probatio.Secret(CONF_API_KEY)): str}
|
||||
),
|
||||
data_schema=STEP_REAUTH_SCHEMA,
|
||||
description_placeholders={"oauth_url": OAUTH_URL},
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@@ -10,3 +10,5 @@ LOGGER = logging.getLogger(__package__)
|
||||
SCAN_INTERVAL = timedelta(minutes=1)
|
||||
|
||||
CONF_TAILNET: Final = "tailnet"
|
||||
CONF_OAUTH_CLIENT_ID: Final = "oauth_client_id"
|
||||
CONF_OAUTH_CLIENT_SECRET: Final = "oauth_client_secret"
|
||||
|
||||
@@ -5,14 +5,20 @@ from typing import override
|
||||
from tailscale import Device, Tailscale, TailscaleAuthenticationError
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
|
||||
from .const import CONF_TAILNET, DOMAIN, LOGGER, SCAN_INTERVAL
|
||||
from .const import (
|
||||
CONF_OAUTH_CLIENT_ID,
|
||||
CONF_OAUTH_CLIENT_SECRET,
|
||||
CONF_TAILNET,
|
||||
DOMAIN,
|
||||
LOGGER,
|
||||
SCAN_INTERVAL,
|
||||
)
|
||||
|
||||
type TailscaleConfigEntry = ConfigEntry[TailscaleDataUpdateCoordinator]
|
||||
|
||||
@@ -27,7 +33,8 @@ class TailscaleDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Device]]):
|
||||
session = async_get_clientsession(hass)
|
||||
self.tailscale = Tailscale(
|
||||
session=session,
|
||||
api_key=config_entry.data[CONF_API_KEY],
|
||||
oauth_client_id=config_entry.data[CONF_OAUTH_CLIENT_ID],
|
||||
oauth_client_secret=config_entry.data[CONF_OAUTH_CLIENT_SECRET],
|
||||
tailnet=config_entry.data[CONF_TAILNET],
|
||||
)
|
||||
self.previous_devices: set[str] = set()
|
||||
|
||||
@@ -7,11 +7,13 @@ from homeassistant.components.diagnostics import async_redact_data
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import CONF_TAILNET
|
||||
from .const import CONF_OAUTH_CLIENT_ID, CONF_OAUTH_CLIENT_SECRET, CONF_TAILNET
|
||||
from .coordinator import TailscaleConfigEntry
|
||||
|
||||
TO_REDACT = {
|
||||
CONF_API_KEY,
|
||||
CONF_OAUTH_CLIENT_ID,
|
||||
CONF_OAUTH_CLIENT_SECRET,
|
||||
CONF_TAILNET,
|
||||
"addresses",
|
||||
"device_id",
|
||||
|
||||
@@ -10,16 +10,18 @@
|
||||
"step": {
|
||||
"reauth_confirm": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
"oauth_client_id": "[%key:component::tailscale::config::step::user::data::oauth_client_id%]",
|
||||
"oauth_client_secret": "[%key:component::tailscale::config::step::user::data::oauth_client_secret%]"
|
||||
},
|
||||
"description": "Tailscale API access tokens are valid for 90-days. You can create a fresh Tailscale API access token at {authkeys_url}."
|
||||
"description": "Enter the credentials of a Tailscale OAuth client so Home Assistant can keep authenticating. Create one at {oauth_url} and grant it the **Devices: Core** read scope.\n\nOAuth clients do not expire, so they do not need to be replaced periodically."
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]",
|
||||
"oauth_client_id": "OAuth client ID",
|
||||
"oauth_client_secret": "OAuth client secret",
|
||||
"tailnet": "Tailnet"
|
||||
},
|
||||
"description": "This integration monitors your Tailscale network, it **DOES NOT** make your Home Assistant accessible via Tailscale VPN. \n\nTo authenticate with Tailscale you'll need to create an API access token at {authkeys_url}.\n\nA Tailnet is the name of your Tailscale network. You can find it in the top left corner in the Tailscale Admin Panel (beside the Tailscale logo)."
|
||||
"description": "This integration monitors your Tailscale network, it **DOES NOT** make your Home Assistant accessible via Tailscale VPN.\n\nA Tailnet is the name of your Tailscale network. You can find it in the top left corner in the Tailscale Admin Panel (beside the Tailscale logo).\n\nCreate an OAuth client at {oauth_url} and grant it the **Devices: Core** read scope. OAuth clients do not expire, so they do not need to be replaced periodically."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -6,7 +6,12 @@ from unittest.mock import AsyncMock, MagicMock, patch
|
||||
import pytest
|
||||
from tailscale.models import Devices
|
||||
|
||||
from homeassistant.components.tailscale.const import CONF_TAILNET, DOMAIN
|
||||
from homeassistant.components.tailscale.const import (
|
||||
CONF_OAUTH_CLIENT_ID,
|
||||
CONF_OAUTH_CLIENT_SECRET,
|
||||
CONF_TAILNET,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
@@ -15,7 +20,22 @@ from tests.common import MockConfigEntry, load_fixture
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Return the default mocked config entry."""
|
||||
"""Return the default mocked config entry, using OAuth client credentials."""
|
||||
return MockConfigEntry(
|
||||
title="homeassistant.github",
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_OAUTH_CLIENT_ID: "tskey-client-MOCK",
|
||||
CONF_OAUTH_CLIENT_SECRET: "mock-oauth-client-secret",
|
||||
},
|
||||
unique_id="homeassistant.github",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry_api_key() -> MockConfigEntry:
|
||||
"""Return a legacy mocked config entry still using an API access token."""
|
||||
return MockConfigEntry(
|
||||
title="homeassistant.github",
|
||||
domain=DOMAIN,
|
||||
|
||||
@@ -5,7 +5,12 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
from tailscale import TailscaleAuthenticationError, TailscaleConnectionError
|
||||
|
||||
from homeassistant.components.tailscale.const import CONF_TAILNET, DOMAIN
|
||||
from homeassistant.components.tailscale.const import (
|
||||
CONF_OAUTH_CLIENT_ID,
|
||||
CONF_OAUTH_CLIENT_SECRET,
|
||||
CONF_TAILNET,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -13,6 +18,13 @@ from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
OAUTH_INPUT = {
|
||||
CONF_OAUTH_CLIENT_ID: "tskey-client-FAKE",
|
||||
CONF_OAUTH_CLIENT_SECRET: "fake-oauth-client-secret",
|
||||
}
|
||||
|
||||
USER_INPUT = {CONF_TAILNET: "homeassistant.github", **OAUTH_INPUT}
|
||||
|
||||
|
||||
async def test_full_user_flow(
|
||||
hass: HomeAssistant,
|
||||
@@ -27,85 +39,67 @@ async def test_full_user_flow(
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "user"
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-FAKE",
|
||||
},
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input=USER_INPUT
|
||||
)
|
||||
|
||||
assert result2.get("type") is FlowResultType.CREATE_ENTRY
|
||||
assert result2.get("title") == "homeassistant.github"
|
||||
assert result2.get("data") == {
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-FAKE",
|
||||
}
|
||||
assert result2["result"].unique_id == "homeassistant.github"
|
||||
assert result.get("type") is FlowResultType.CREATE_ENTRY
|
||||
assert result.get("title") == "homeassistant.github"
|
||||
assert result.get("data") == USER_INPUT
|
||||
assert result["result"].unique_id == "homeassistant.github"
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.close.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_full_flow_with_authentication_error(
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "reason"),
|
||||
[
|
||||
pytest.param(
|
||||
TailscaleAuthenticationError, "invalid_auth", id="authentication_error"
|
||||
),
|
||||
pytest.param(TailscaleConnectionError, "cannot_connect", id="connection_error"),
|
||||
],
|
||||
)
|
||||
async def test_full_flow_with_error(
|
||||
hass: HomeAssistant,
|
||||
mock_tailscale_config_flow: MagicMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
side_effect: type[Exception],
|
||||
reason: str,
|
||||
) -> None:
|
||||
"""Test the full user configuration flow with incorrect API key.
|
||||
|
||||
This tests tests a full config flow, with a case the user enters an invalid
|
||||
Tailscale API key, but recovers by entering the correct one.
|
||||
"""
|
||||
"""Test the user flow recovering from an error entering credentials."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = side_effect
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input=USER_INPUT
|
||||
)
|
||||
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "user"
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = TailscaleAuthenticationError
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-INVALID",
|
||||
},
|
||||
)
|
||||
|
||||
assert result2.get("type") is FlowResultType.FORM
|
||||
assert result2.get("step_id") == "user"
|
||||
assert result2.get("errors") == {"base": "invalid_auth"}
|
||||
|
||||
assert result.get("errors") == {"base": reason}
|
||||
assert len(mock_setup_entry.mock_calls) == 0
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 1
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = None
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
result2["flow_id"],
|
||||
user_input={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-VALID",
|
||||
},
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input=USER_INPUT
|
||||
)
|
||||
|
||||
assert result3.get("type") is FlowResultType.CREATE_ENTRY
|
||||
assert result3.get("title") == "homeassistant.github"
|
||||
assert result3.get("data") == {
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-VALID",
|
||||
}
|
||||
|
||||
assert result.get("type") is FlowResultType.CREATE_ENTRY
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_connection_error(
|
||||
hass: HomeAssistant, mock_tailscale_config_flow: MagicMock
|
||||
async def test_already_configured(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test API connection error."""
|
||||
mock_tailscale_config_flow.devices.side_effect = TailscaleConnectionError
|
||||
"""Test the tailnet is only allowed to be configured once."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
@@ -115,28 +109,11 @@ async def test_connection_error(
|
||||
assert result.get("step_id") == "user"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-FAKE",
|
||||
},
|
||||
result["flow_id"], user_input=USER_INPUT
|
||||
)
|
||||
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("errors") == {"base": "cannot_connect"}
|
||||
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 1
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-FAKE",
|
||||
},
|
||||
)
|
||||
|
||||
assert result.get("type") is FlowResultType.CREATE_ENTRY
|
||||
assert result.get("type") is FlowResultType.ABORT
|
||||
assert result.get("reason") == "already_configured"
|
||||
|
||||
|
||||
async def test_reauth_flow(
|
||||
@@ -145,109 +122,98 @@ async def test_reauth_flow(
|
||||
mock_tailscale_config_flow: MagicMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
) -> None:
|
||||
"""Test the reauthentication configuration flow."""
|
||||
"""Test reauthentication of an entry using OAuth client credentials."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "reauth_confirm"
|
||||
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: "tskey-REAUTH"},
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], OAUTH_INPUT
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2.get("type") is FlowResultType.ABORT
|
||||
assert result2.get("reason") == "reauth_successful"
|
||||
assert result.get("type") is FlowResultType.ABORT
|
||||
assert result.get("reason") == "reauth_successful"
|
||||
assert mock_config_entry.data == {
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-REAUTH",
|
||||
**OAUTH_INPUT,
|
||||
}
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.close.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_reauth_with_authentication_error(
|
||||
@pytest.mark.usefixtures("mock_tailscale_config_flow", "mock_setup_entry")
|
||||
async def test_reauth_flow_migrates_api_key_entry(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry_api_key: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test reauthentication migrates a legacy API access token entry to OAuth."""
|
||||
mock_config_entry_api_key.add_to_hass(hass)
|
||||
|
||||
result = await mock_config_entry_api_key.start_reauth_flow(hass)
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "reauth_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], OAUTH_INPUT
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result.get("type") is FlowResultType.ABORT
|
||||
assert result.get("reason") == "reauth_successful"
|
||||
assert mock_config_entry_api_key.data == {
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
**OAUTH_INPUT,
|
||||
}
|
||||
assert CONF_API_KEY not in mock_config_entry_api_key.data
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "reason"),
|
||||
[
|
||||
pytest.param(
|
||||
TailscaleAuthenticationError, "invalid_auth", id="authentication_error"
|
||||
),
|
||||
pytest.param(TailscaleConnectionError, "cannot_connect", id="connection_error"),
|
||||
],
|
||||
)
|
||||
async def test_reauth_with_error(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_tailscale_config_flow: MagicMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
side_effect: type[Exception],
|
||||
reason: str,
|
||||
) -> None:
|
||||
"""Test the reauthentication configuration flow with an authentication error.
|
||||
|
||||
This tests tests a reauth flow, with a case the user enters an invalid
|
||||
API key, but recover by entering the correct one.
|
||||
"""
|
||||
"""Test the reauth flow recovering from an error."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = side_effect
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], OAUTH_INPUT
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "reauth_confirm"
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = TailscaleAuthenticationError
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: "tskey-INVALID"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2.get("type") is FlowResultType.FORM
|
||||
assert result2.get("step_id") == "reauth_confirm"
|
||||
assert result2.get("errors") == {"base": "invalid_auth"}
|
||||
|
||||
assert result.get("errors") == {"base": reason}
|
||||
assert len(mock_setup_entry.mock_calls) == 0
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 1
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = None
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
result2["flow_id"],
|
||||
user_input={CONF_API_KEY: "tskey-VALID"},
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input=OAUTH_INPUT
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result3.get("type") is FlowResultType.ABORT
|
||||
assert result3.get("reason") == "reauth_successful"
|
||||
assert result.get("type") is FlowResultType.ABORT
|
||||
assert result.get("reason") == "reauth_successful"
|
||||
assert mock_config_entry.data == {
|
||||
CONF_TAILNET: "homeassistant.github",
|
||||
CONF_API_KEY: "tskey-VALID",
|
||||
**OAUTH_INPUT,
|
||||
}
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
assert len(mock_tailscale_config_flow.devices.mock_calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_setup_entry")
|
||||
async def test_reauth_api_error(
|
||||
hass: HomeAssistant,
|
||||
mock_tailscale_config_flow: MagicMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test API error during reauthentication."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
assert result.get("type") is FlowResultType.FORM
|
||||
assert result.get("step_id") == "reauth_confirm"
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = TailscaleConnectionError
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: "tskey-VALID"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2.get("type") is FlowResultType.FORM
|
||||
assert result2.get("step_id") == "reauth_confirm"
|
||||
assert result2.get("errors") == {"base": "cannot_connect"}
|
||||
|
||||
mock_tailscale_config_flow.devices.side_effect = None
|
||||
result3 = await hass.config_entries.flow.async_configure(
|
||||
result2["flow_id"],
|
||||
{CONF_API_KEY: "tskey-VALID"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result3.get("type") is FlowResultType.ABORT
|
||||
assert result3.get("reason") == "reauth_successful"
|
||||
|
||||
@@ -28,6 +28,7 @@ async def test_load_unload_config_entry(
|
||||
|
||||
assert not hass.data.get(DOMAIN)
|
||||
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
mock_tailscale.close.assert_called_once()
|
||||
|
||||
|
||||
async def test_config_entry_not_ready(
|
||||
@@ -44,6 +45,7 @@ async def test_config_entry_not_ready(
|
||||
|
||||
assert len(mock_tailscale.devices.mock_calls) == 1
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
mock_tailscale.close.assert_called_once()
|
||||
|
||||
|
||||
async def test_config_entry_authentication_failed(
|
||||
@@ -71,3 +73,24 @@ async def test_config_entry_authentication_failed(
|
||||
assert "context" in flow
|
||||
assert flow["context"].get("source") == SOURCE_REAUTH
|
||||
assert flow["context"].get("entry_id") == mock_config_entry.entry_id
|
||||
|
||||
|
||||
async def test_api_key_entry_triggers_migration_reauth(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry_api_key: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test a legacy API access token entry is migrated to OAuth via reauth."""
|
||||
mock_config_entry_api_key.add_to_hass(hass)
|
||||
await hass.config_entries.async_setup(mock_config_entry_api_key.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry_api_key.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
|
||||
flow = flows[0]
|
||||
assert flow.get("step_id") == "reauth_confirm"
|
||||
assert flow.get("handler") == DOMAIN
|
||||
assert flow["context"].get("source") == SOURCE_REAUTH
|
||||
assert flow["context"].get("entry_id") == mock_config_entry_api_key.entry_id
|
||||
|
||||
Reference in New Issue
Block a user