fix: make reauth update the existing entry instead of aborting
async_step_token is shared by the user and reauth sources but was written only for the former. It called _abort_if_unique_id_configured() on every path, and during reauth the unique ID belongs to the entry being repaired, so the duplicate guard fired by design: authentication succeeded, the flow aborted with already_configured, the new tokens were discarded, and the coordinator's next poll re-raised the reauth repair. The integration was unrecoverable through the UI short of delete-and-re-add, which costs entity history and the restored keg-freshness baseline. Branch on self.source at the terminal step, per HA's documented pattern for flows shared between setup and reauth: reauth now guards with _abort_if_unique_id_mismatch() and persists through async_update_reload_and_abort(), which merges the new tokens into the existing entry, keeps email and machine ID, reloads, and aborts with reauth_successful. The user path keeps _abort_if_unique_id_configured() unchanged. Reauth also stops re-fetching /api/me when the entry already records a machine ID, removing a round trip from a flow the user waits on and a failure mode where a transient /api/me error turned a successful sign-in into cannot_connect. The helpers require core 2024.11, so declare that floor in hacs.json — otherwise older cores would AttributeError mid-flow, which is worse than the bug being fixed. Adds the repo's first HA test harness (requirements-test.txt, opt-in) with regression tests covering token persistence, entry reload, account mismatch, case-insensitive email, and the explicit assertion that reauth never aborts as already_configured. tests/test_keg_detection.py still runs standalone under python3 -m unittest. Version set to 0.3.1 rather than the 0.4.0 that PR #2 introduced; no v0.4.0 tag was ever cut, so nothing was released under that number. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -4,6 +4,8 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.venv-test/
|
||||
.pytest_cache/
|
||||
.credentials.json
|
||||
*.swp
|
||||
custom_components/perfectdraft.zip
|
||||
|
||||
@@ -89,25 +89,27 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
_LOGGER.error("API error during auth: %s", err)
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
reauth_entry = (
|
||||
self._get_reauth_entry()
|
||||
if self.source == config_entries.SOURCE_REAUTH
|
||||
else None
|
||||
)
|
||||
machine_id = (
|
||||
reauth_entry.data.get(CONF_MACHINE_ID) if reauth_entry else None
|
||||
)
|
||||
|
||||
if machine_id:
|
||||
return await self._async_persist(
|
||||
client, reauth_entry, machine_id
|
||||
)
|
||||
|
||||
try:
|
||||
profile = await client.get_user_profile()
|
||||
except (PerfectDraftApiError, PerfectDraftConnectionError):
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
machine_id = _extract_machine_id(profile)
|
||||
|
||||
await self.async_set_unique_id(self._email.lower())
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
return self.async_create_entry(
|
||||
title=f"PerfectDraft ({self._email})",
|
||||
data={
|
||||
CONF_EMAIL: self._email,
|
||||
CONF_ACCESS_TOKEN: client.access_token,
|
||||
CONF_ID_TOKEN: client.id_token,
|
||||
CONF_REFRESH_TOKEN: client.refresh_token,
|
||||
CONF_MACHINE_ID: machine_id,
|
||||
},
|
||||
return await self._async_persist(
|
||||
client, reauth_entry, _extract_machine_id(profile)
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
@@ -120,6 +122,41 @@ class PerfectDraftConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def _async_persist(
|
||||
self,
|
||||
client: PerfectDraftApiClient,
|
||||
reauth_entry: config_entries.ConfigEntry | None,
|
||||
machine_id: str | None,
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
"""Store the freshly issued tokens.
|
||||
|
||||
Reauth must update the entry it was started for. Creating a new one
|
||||
would change the entry_id and orphan every entity's unique_id, and
|
||||
`_abort_if_unique_id_configured` cannot be used here at all: during
|
||||
reauth the unique ID belongs to that very entry, so the duplicate
|
||||
guard would abort the flow and discard the new tokens.
|
||||
"""
|
||||
data = {
|
||||
CONF_ACCESS_TOKEN: client.access_token,
|
||||
CONF_ID_TOKEN: client.id_token,
|
||||
CONF_REFRESH_TOKEN: client.refresh_token,
|
||||
CONF_MACHINE_ID: machine_id,
|
||||
}
|
||||
|
||||
await self.async_set_unique_id(self._email.lower())
|
||||
|
||||
if reauth_entry is not None:
|
||||
self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
|
||||
return self.async_update_reload_and_abort(
|
||||
reauth_entry, data_updates=data
|
||||
)
|
||||
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title=f"PerfectDraft ({self._email})",
|
||||
data={CONF_EMAIL: self._email, **data},
|
||||
)
|
||||
|
||||
async def async_step_reauth(
|
||||
self, entry_data: dict[str, Any]
|
||||
) -> config_entries.ConfigFlowResult:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "perfectdraft",
|
||||
"name": "PerfectDraft",
|
||||
"version": "0.4.0",
|
||||
"version": "0.3.1",
|
||||
"documentation": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro",
|
||||
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-perfectdraft-pro/issues",
|
||||
"codeowners": ["@Falkvinge"],
|
||||
|
||||
@@ -32,7 +32,8 @@
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "This PerfectDraft account is already configured.",
|
||||
"reauth_successful": "Re-authentication successful."
|
||||
"reauth_successful": "Re-authentication successful.",
|
||||
"reauth_account_mismatch": "Those credentials are for a different PerfectDraft account. Re-authenticate with the account this integration was set up with, or delete the integration and add the other account separately."
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
|
||||
@@ -32,7 +32,8 @@
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "This PerfectDraft account is already configured.",
|
||||
"reauth_successful": "Re-authentication successful."
|
||||
"reauth_successful": "Re-authentication successful.",
|
||||
"reauth_account_mismatch": "Those credentials are for a different PerfectDraft account. Re-authenticate with the account this integration was set up with, or delete the integration and add the other account separately."
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"name": "PerfectDraft",
|
||||
"render_readme": true
|
||||
"render_readme": true,
|
||||
"homeassistant": "2024.11.0"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
pythonpath = .
|
||||
asyncio_mode = auto
|
||||
asyncio_default_fixture_loop_scope = function
|
||||
@@ -0,0 +1,18 @@
|
||||
# Test-only dependencies. The integration itself stays dependency-free
|
||||
# (manifest.json keeps "requirements": []); this harness exists because
|
||||
# config-flow behaviour cannot be exercised without a real Home Assistant.
|
||||
#
|
||||
# pytest-homeassistant-custom-component releases track core one-to-one.
|
||||
# 0.13.205 is the newest release that still supports Python 3.12 and it
|
||||
# pins core 2025.1.4 — above the 2024.11 floor the reauth helpers need.
|
||||
#
|
||||
# python3 -m venv .venv-test
|
||||
# .venv-test/bin/pip install -r requirements-test.txt
|
||||
# .venv-test/bin/pytest tests/
|
||||
pytest-homeassistant-custom-component==0.13.205
|
||||
|
||||
# Core pins aiodns==3.2.0 but leaves pycares floating. pycares 4.6+ starts a
|
||||
# daemon shutdown thread that the harness's verify_cleanup fixture flags as a
|
||||
# leak, failing every test at teardown. 4.5.0 is contemporaneous with core
|
||||
# 2025.1.4 and has no such thread.
|
||||
pycares==4.5.0
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Fixtures for the Home Assistant test harness.
|
||||
|
||||
Only the pytest suite uses this. ``test_keg_detection.py`` imports the
|
||||
Home-Assistant-free ``keg_detection`` module and still runs standalone under
|
||||
``python3 -m unittest discover -s tests``.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
pytest_plugins = "pytest_homeassistant_custom_component"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def auto_enable_custom_integrations(enable_custom_integrations):
|
||||
"""Make custom_components/perfectdraft loadable in every test."""
|
||||
yield
|
||||
@@ -0,0 +1,301 @@
|
||||
"""Config flow tests, focused on the reauth path.
|
||||
|
||||
The bug these guard against: ``async_step_token`` is shared by the user and
|
||||
reauth sources, and used to call ``_abort_if_unique_id_configured()``
|
||||
unconditionally. During reauth the unique ID belongs to the entry being
|
||||
repaired, so the duplicate guard aborted the flow with ``already_configured``
|
||||
and the freshly issued tokens were discarded.
|
||||
"""
|
||||
import unittest
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
try:
|
||||
import pytest
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.perfectdraft.const import (
|
||||
CONF_ACCESS_TOKEN,
|
||||
CONF_ID_TOKEN,
|
||||
CONF_MACHINE_ID,
|
||||
CONF_REFRESH_TOKEN,
|
||||
DOMAIN,
|
||||
)
|
||||
from custom_components.perfectdraft.exceptions import (
|
||||
AuthenticationError,
|
||||
PerfectDraftConnectionError,
|
||||
)
|
||||
except ImportError as err:
|
||||
# Keeps `python3 -m unittest discover -s tests` working for anyone who
|
||||
# only wants the stdlib-only keg-detection tests: unittest turns a
|
||||
# SkipTest raised during import into a skip rather than an error.
|
||||
raise unittest.SkipTest(
|
||||
"Home Assistant test harness missing "
|
||||
"(pip install -r requirements-test.txt)"
|
||||
) from err
|
||||
|
||||
EMAIL = "drinker@example.com"
|
||||
PASSWORD = "hunter2"
|
||||
TOKEN = "recaptcha-token"
|
||||
MACHINE_ID = "machine-1"
|
||||
|
||||
CLIENT_PATH = "custom_components.perfectdraft.config_flow.PerfectDraftApiClient"
|
||||
SETUP_PATH = "custom_components.perfectdraft.async_setup_entry"
|
||||
|
||||
STORED_DATA = {
|
||||
CONF_EMAIL: EMAIL,
|
||||
CONF_ACCESS_TOKEN: "old-access",
|
||||
CONF_ID_TOKEN: "old-id",
|
||||
CONF_REFRESH_TOKEN: "old-refresh",
|
||||
CONF_MACHINE_ID: MACHINE_ID,
|
||||
}
|
||||
|
||||
|
||||
def _mock_client(*, authenticate_error=None, machines=((MACHINE_ID,))):
|
||||
"""An API client that hands back recognisably new tokens."""
|
||||
client = AsyncMock()
|
||||
client.access_token = "new-access"
|
||||
client.id_token = "new-id"
|
||||
client.refresh_token = "new-refresh"
|
||||
if authenticate_error is not None:
|
||||
client.authenticate.side_effect = authenticate_error
|
||||
client.get_user_profile.return_value = {
|
||||
"perfectdraftMachines": [{"id": m} for m in machines]
|
||||
}
|
||||
return client
|
||||
|
||||
|
||||
def _entry(hass: HomeAssistant, data=None, unique_id=EMAIL) -> MockConfigEntry:
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id=unique_id,
|
||||
data=dict(STORED_DATA if data is None else data),
|
||||
title=f"PerfectDraft ({EMAIL})",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return entry
|
||||
|
||||
|
||||
async def _run_reauth(hass, entry, client, *, email=EMAIL, token=TOKEN):
|
||||
"""Drive reauth_confirm then token, returning the final flow result."""
|
||||
with (
|
||||
patch(CLIENT_PATH, return_value=client),
|
||||
patch(SETUP_PATH, return_value=True),
|
||||
):
|
||||
result = await 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_EMAIL: email, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "token"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": token}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
return result
|
||||
|
||||
|
||||
# --- Reauth: the regression this change fixes ---
|
||||
|
||||
|
||||
async def test_reauth_persists_new_tokens(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
result = await _run_reauth(hass, entry, _mock_client())
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
|
||||
assert entry.data[CONF_ID_TOKEN] == "new-id"
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == "new-refresh"
|
||||
|
||||
|
||||
async def test_reauth_preserves_email_and_machine_id(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
await _run_reauth(hass, entry, _mock_client())
|
||||
|
||||
assert entry.data[CONF_EMAIL] == EMAIL
|
||||
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
|
||||
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
|
||||
|
||||
|
||||
async def test_reauth_never_aborts_as_already_configured(hass: HomeAssistant) -> None:
|
||||
"""The exact failure reported: auth succeeds, then the flow dies here."""
|
||||
entry = _entry(hass)
|
||||
result = await _run_reauth(hass, entry, _mock_client())
|
||||
|
||||
assert result["reason"] != "already_configured"
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
|
||||
async def test_reauth_reloads_the_entry(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client()
|
||||
|
||||
with (
|
||||
patch(CLIENT_PATH, return_value=client),
|
||||
patch(SETUP_PATH, return_value=True) as mock_setup,
|
||||
):
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_setup.call_count == 1
|
||||
|
||||
|
||||
async def test_reauth_rejects_a_different_account(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
result = await _run_reauth(
|
||||
hass, entry, _mock_client(), email="someone.else@example.com"
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_account_mismatch"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
|
||||
|
||||
|
||||
async def test_reauth_accepts_same_account_different_case(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
entry = _entry(hass)
|
||||
result = await _run_reauth(hass, entry, _mock_client(), email="Drinker@Example.COM")
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "new-access"
|
||||
|
||||
|
||||
async def test_reauth_bad_token_keeps_old_tokens(hass: HomeAssistant) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client(authenticate_error=AuthenticationError("token expired"))
|
||||
result = await _run_reauth(hass, entry, client)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "token"
|
||||
assert result["errors"] == {"base": "invalid_auth"}
|
||||
assert entry.data[CONF_ACCESS_TOKEN] == "old-access"
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == "old-refresh"
|
||||
|
||||
|
||||
async def test_reauth_skips_profile_when_machine_id_known(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
entry = _entry(hass)
|
||||
client = _mock_client()
|
||||
await _run_reauth(hass, entry, client)
|
||||
|
||||
client.get_user_profile.assert_not_called()
|
||||
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
|
||||
|
||||
|
||||
async def test_reauth_recovers_missing_machine_id(hass: HomeAssistant) -> None:
|
||||
data = {k: v for k, v in STORED_DATA.items() if k != CONF_MACHINE_ID}
|
||||
entry = _entry(hass, data=data)
|
||||
client = _mock_client()
|
||||
await _run_reauth(hass, entry, client)
|
||||
|
||||
client.get_user_profile.assert_called_once()
|
||||
assert entry.data[CONF_MACHINE_ID] == MACHINE_ID
|
||||
|
||||
|
||||
# --- User setup: must be unchanged by this fix ---
|
||||
|
||||
|
||||
async def test_user_setup_creates_entry(hass: HomeAssistant) -> None:
|
||||
client = _mock_client()
|
||||
|
||||
with (
|
||||
patch(CLIENT_PATH, return_value=client),
|
||||
patch(SETUP_PATH, return_value=True),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
assert result["step_id"] == "user"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
assert result["step_id"] == "token"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_ACCESS_TOKEN] == "new-access"
|
||||
assert result["data"][CONF_MACHINE_ID] == MACHINE_ID
|
||||
assert result["result"].unique_id == EMAIL
|
||||
|
||||
|
||||
async def test_user_setup_still_blocks_duplicates(hass: HomeAssistant) -> None:
|
||||
_entry(hass)
|
||||
client = _mock_client()
|
||||
|
||||
with (
|
||||
patch(CLIENT_PATH, return_value=client),
|
||||
patch(SETUP_PATH, return_value=True),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
async def test_user_setup_connection_error(hass: HomeAssistant) -> None:
|
||||
client = _mock_client(
|
||||
authenticate_error=PerfectDraftConnectionError("no route to host")
|
||||
)
|
||||
|
||||
with patch(CLIENT_PATH, return_value=client):
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_EMAIL: EMAIL, CONF_PASSWORD: PASSWORD}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {"recaptcha_token": TOKEN}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
|
||||
# --- Translations must cover every reachable abort reason ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reason",
|
||||
["already_configured", "reauth_successful", "reauth_account_mismatch"],
|
||||
)
|
||||
def test_abort_reasons_are_translated(reason: str) -> None:
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).parent.parent / "custom_components" / "perfectdraft"
|
||||
for name in ("strings.json", "translations/en.json"):
|
||||
data = json.loads((root / name).read_text(encoding="utf-8"))
|
||||
assert reason in data["config"]["abort"], f"{reason} missing from {name}"
|
||||
Reference in New Issue
Block a user