openspec(fix-reauth-flow): propose artifacts

Reauth aborts with already_configured because async_step_token calls
_abort_if_unique_id_configured() on every source, including reauth where
a matching unique ID is the expected condition. Fresh tokens are discarded
and the entry stays broken.

Artifacts cover the source-aware fix, the 2024.11 core floor the reauth
helpers require, and the pytest-homeassistant-custom-component harness
needed to regression-test a config flow.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-09-06 15:13:18 +02:00
co-authored by Cursor
parent 3b69942542
commit 4ff26f6e7b
5 changed files with 301 additions and 0 deletions
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-09-06
+126
View File
@@ -0,0 +1,126 @@
## Context
The config flow has three entry points that converge on one terminal step:
```
async_step_user ──────────────┐
├──> async_step_token ──> async_create_entry
async_step_reauth ──> async_step_reauth_confirm ──┘
```
`async_step_token` is the only place that talks to the API and the only place that persists tokens. It was written for the initial-setup path and never made aware that reauth also lands there:
```100:111:custom_components/perfectdraft/config_flow.py
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,
},
)
```
During reauth the unique ID resolves to the entry being repaired, so `_abort_if_unique_id_configured()` fires and the flow terminates with `already_configured` before reaching `async_create_entry`. This is the documented behaviour of that helper — it is simply the wrong helper for this source. The observed symptom chain follows directly: authentication succeeds (the "churning"), the abort surfaces "already configured", the entry retains its dead tokens, and the coordinator's next `ConfigEntryAuthFailed` re-raises the reauth repair.
Constraints on the fix:
- The reauth path must reach the *same* API calls as setup. PerfectDraft's `/authentication/sign-in` requires a fresh reCAPTCHA token with a two-minute lifetime, so reauth genuinely needs the full email/password/token sequence — there is no silent re-auth to fall back on. Sharing `async_step_token` between sources is correct; only its terminal branch is wrong.
- The entry must be preserved, not recreated. Recreating would change `entry_id`, orphan every entity's `unique_id`, and discard the keg-freshness baseline that `PerfectDraftKegFreshnessSensor` restores via `RestoreEntity`.
- `CONF_MACHINE_ID` already lives in the entry. Reauth should not depend on rediscovering it.
## Goals / Non-Goals
**Goals:**
- Reauth completes: fresh tokens land in the existing config entry, the entry reloads, the repair clears.
- Reauth can never abort with `already_configured`.
- Signing in as a different account during reauth is rejected with a clear message, not silently rebound onto the existing entry.
- The initial-setup path behaves exactly as it does today, including duplicate prevention.
- Automated regression coverage for all of the above.
**Non-Goals:**
- Persisting Cognito-refreshed access/ID tokens back to the config entry during normal polling. Noted in the proposal, tracked separately.
- Eliminating the reCAPTCHA token requirement from reauth. The upstream API mandates it.
- A `reconfigure` step. Nothing in the entry data is user-editable outside of credentials.
- Any change to token refresh, coordinator, or entity behaviour.
## Decisions
### Decision 1: Branch inside `async_step_token` on `self.source`, using HA's reauth helpers
The terminal branch becomes:
```python
await self.async_set_unique_id(self._email.lower())
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={
CONF_ACCESS_TOKEN: client.access_token,
CONF_ID_TOKEN: client.id_token,
CONF_REFRESH_TOKEN: client.refresh_token,
},
)
self._abort_if_unique_id_configured()
return self.async_create_entry(...)
```
This is verbatim the pattern Home Assistant's developer documentation prescribes for flows whose steps are shared between `user` and `reauth` sources. `data_updates` merges into the existing entry data, so `CONF_EMAIL` and `CONF_MACHINE_ID` survive untouched. `async_update_reload_and_abort` reloads the entry and aborts with `reauth_successful` by default, which is exactly the desired terminal state and is already translated in `strings.json`.
*Alternative considered — a separate reauth-specific token step.* Duplicating the authenticate/profile/error-handling block into `async_step_reauth_token` would avoid the source check, but it clones roughly forty lines of error handling that must then stay in sync across two paths. The bug being fixed here is precisely a divergence between setup and reauth expectations; duplicating the code invites the next one.
*Alternative considered — hand-rolled entry update for pre-2024.11 compatibility.* `self.hass.config_entries.async_get_entry(self.context["entry_id"])`, a manual unique-ID comparison, `async_update_entry`, `async_reload`, and `self.async_abort(reason="reauth_successful")` reproduce the helpers' behaviour on older cores. Rejected: it is more code, it is the pattern HA explicitly deprecated in favour of the helpers, and 2024.11 shipped in November 2024 — a floor that is nearly two years old.
### Decision 2: Declare `"homeassistant": "2024.11.0"` in `hacs.json`
`_get_reauth_entry`, `_abort_if_unique_id_mismatch`, and the `data_updates` parameter of `async_update_reload_and_abort` all landed in Home Assistant Core 2024.11. The repo currently declares no minimum core version anywhere, so on an older core the fix would fail with an `AttributeError` mid-flow — a worse failure than the bug it replaces. HACS reads the `homeassistant` key and blocks installation below that floor, turning a runtime crash into an install-time message.
Note this belongs in `hacs.json`, not `manifest.json`: integration manifests have no minimum-core-version field.
### Decision 3: Custom abort reason `reauth_account_mismatch` over the default
`_abort_if_unique_id_mismatch()` defaults to reason `unique_id_mismatch`. Either reason needs a corresponding entry under `config.abort` in `strings.json` and `translations/en.json`, since custom components cannot use core's `[%key:common::...]` translation references. Given a string must be written regardless, the specific reason carries the actionable message — the user re-entered a different account's email and needs to use the original one, or delete the entry and add the new account fresh.
### Decision 4: Test with `pytest-homeassistant-custom-component`
Config-flow behaviour cannot be verified without instantiating Home Assistant: the failure is in `ConfigFlow` helper interaction, not in any extractable pure function. `pytest-homeassistant-custom-component` is the standard harness for custom integrations and provides `hass`, `MockConfigEntry`, and the flow-driving helpers needed to assert on abort reasons and post-flow entry data.
This adds the repo's first dev dependency. It goes in a new `requirements-test.txt` so the runtime component stays dependency-free (`manifest.json` keeps `"requirements": []`), and the existing stdlib-only `test_keg_detection.py` continues to run under plain `python3 -m unittest` for anyone who does not install the harness.
The harness version must be pinned to match a core version at or above the 2024.11 floor; `pytest-homeassistant-custom-component` releases track core releases one-to-one.
*Alternative considered — stubbing HA modules with `unittest.mock`.* Cheap, no dependency, and worthless here: the bug lives in the real behaviour of `_abort_if_unique_id_configured` against a real config entry registry. A stub would encode our assumption about that helper rather than test it, and would have passed against the broken code.
### Decision 5: Keep the profile lookup conditional on a missing machine ID
Reauth currently re-fetches `/api/me` to extract the machine ID, then discards it in the abort. Since `data_updates` preserves the stored `CONF_MACHINE_ID`, the call is redundant on the reauth path whenever the entry already has one. Skipping it removes a network round trip from a flow the user is actively waiting on, and removes a failure mode where a transient `/api/me` error turns a successful authentication into `cannot_connect`. The lookup is retained when the entry has no machine ID recorded, which keeps the reauth path capable of healing an entry that was created before a machine was registered.
## Risks / Trade-offs
**The 2024.11 floor excludes users on older cores.** → Two years of core releases is a generous floor for an integration whose current release is 0.3.0, and HACS surfaces the requirement at install time rather than as a runtime crash. Users below it are already missing security fixes.
**`self.source` is unreliable if a step is reached by an unanticipated route.** → The flow has exactly three entry points, all enumerated above, and `SOURCE_REAUTH` is set by Home Assistant itself when it starts the repair. The `else` branch retains `_abort_if_unique_id_configured()`, so any unforeseen source keeps today's conservative duplicate-prevention behaviour rather than silently overwriting an entry.
**Email case sensitivity determines whether the mismatch guard fires correctly.** → `async_set_unique_id(self._email.lower())` already normalises, and the stored unique ID was written by the same expression at setup time. The reauth form pre-fills the stored email, so the common path compares identical strings. A test asserting that a differently-cased re-entry of the *same* address is accepted pins this down.
**Adding a test dependency risks breaking the existing lightweight test run.** → `requirements-test.txt` is opt-in and `test_keg_detection.py` keeps its stdlib-only imports, so `python3 -m unittest discover -s tests` continues to work standalone. Verification during implementation must confirm both runners pass.
## Migration Plan
No data migration. The config entry schema is unchanged — `VERSION` stays 1 and `async_migrate_entry` is untouched — because only the *values* of the token fields are refreshed.
Deployment is a normal integration update. Users currently stuck in the reauth loop recover by re-running reauth after updating; no delete-and-re-add is required, and entity history plus the keg-freshness baseline are preserved. Rollback is reverting the commit: it restores the bug but corrupts nothing, since entries written by the fixed code are schema-identical to entries written by the broken code.
## Open Questions
None blocking. The one deferred item — persisting Cognito-refreshed tokens back to the config entry — is recorded in the proposal's Impact section for a separate change.
@@ -0,0 +1,33 @@
## Why
Re-authentication is broken. When the coordinator raises `ConfigEntryAuthFailed`, Home Assistant starts a reauth flow; the user re-enters credentials and a fresh verification token, authentication against the PerfectDraft API succeeds — and then the flow aborts with `already_configured`. The freshly minted tokens are thrown away, the config entry keeps its expired tokens, and HA immediately re-raises the "please re-authenticate" repair. The integration is unrecoverable through the UI: the only way back is to delete and re-add the entry, losing entity history and the restored keg-freshness baseline.
Root cause: `async_step_reauth_confirm` delegates to `async_step_token`, which is written exclusively for the initial-setup path. It unconditionally calls `async_set_unique_id(email)` followed by `_abort_if_unique_id_configured()` and then `async_create_entry()`. During reauth the unique ID *is* already configured — by the very entry being repaired — so the duplicate guard fires by design and the flow dies before it can persist anything.
## What Changes
- `async_step_token` becomes reauth-aware: on a successful authentication it either creates a new entry (initial setup, unchanged behaviour) or updates the existing entry and reloads it (reauth).
- On the reauth path, the duplicate-prevention guard `_abort_if_unique_id_configured()` is replaced by an identity guard that verifies the re-entered email still resolves to the entry under repair, so signing in with a *different* account during reauth is rejected rather than silently rebinding the entry.
- Successful reauth writes the new access, ID, and refresh tokens into the existing entry's data, preserves the already-discovered machine ID, reloads the entry, and aborts with `reauth_successful`.
- Reauth no longer re-derives the machine ID unnecessarily; the profile lookup is only needed when the entry has no machine ID recorded.
- One new abort string (`reauth_account_mismatch`) is added to `strings.json` and `translations/en.json` to explain the account-mismatch rejection. `reauth_successful` and `already_configured` already exist.
- Regression tests cover the reauth path so the `already_configured` abort cannot silently return.
## Capabilities
### New Capabilities
None. This change fixes behaviour already specified.
### Modified Capabilities
- `config-flow`: the existing "Reauth flow" requirement asserts that "on success, the config entry SHALL be updated with new tokens" — behaviour the implementation never had. The requirement is tightened into testable scenarios covering token persistence, entry reload, account-mismatch rejection, and the explicit prohibition on aborting with `already_configured` during reauth. The "Unique ID prevents duplicates" requirement is scoped to the user-initiated setup path so it no longer reads as applying to reauth.
## Impact
- `custom_components/perfectdraft/config_flow.py` — `async_step_token`, `async_step_reauth`, `async_step_reauth_confirm`.
- `custom_components/perfectdraft/strings.json` and `translations/en.json` — one new abort string.
- `hacs.json` — the fix uses config-flow helpers (`_get_reauth_entry`, `_abort_if_unique_id_mismatch`, `async_update_reload_and_abort` with `data_updates`) introduced in Home Assistant Core 2024.11, so a minimum core version is declared rather than left implicit.
- `tests/` — new test module for the config flow. Existing tests are stdlib-only (`test_keg_detection.py` imports the HA-free `keg_detection` module); config-flow tests need Home Assistant plus `pytest-homeassistant-custom-component`, so the test approach is a design decision, not a given.
- No API client, coordinator, or entity changes. No config entry version bump: the data schema is unchanged, only its contents are refreshed.
- Out of scope, noted while investigating: `PerfectDraftApiClient.refresh_access_token()` updates tokens in memory only and never writes them back to the config entry, so every HA restart burns one wasted 401-plus-refresh round trip. Harmless today because the Cognito refresh token is what actually gates reauth, and it is unchanged by a refresh. Tracked separately rather than bundled here.
@@ -0,0 +1,77 @@
## MODIFIED Requirements
### Requirement: Unique ID prevents duplicates
The config flow SHALL set a unique ID based on the lowercased user email. On the user-initiated setup path the flow SHALL abort when that unique ID already belongs to a configured entry. This duplicate guard SHALL NOT be applied on the reauth path, where a matching unique ID is the expected condition rather than a conflict.
#### Scenario: Duplicate prevention on user setup
- **WHEN** a user attempts to add the integration with an email that is already configured
- **THEN** the config flow SHALL abort with reason `already_configured`
#### Scenario: Unique ID normalisation
- **WHEN** the unique ID is set from a submitted email
- **THEN** it SHALL be the lowercased email, so that the same account entered with different capitalisation resolves to the same unique ID
#### Scenario: Duplicate guard not applied during reauth
- **WHEN** the flow reaches the token step with source `reauth`
- **THEN** the flow SHALL NOT abort with reason `already_configured`
### Requirement: Reauth flow
The integration SHALL support Home Assistant's reauth mechanism when the refresh token expires. A successful reauth SHALL update the existing config entry in place, reload it, and abort with `reauth_successful`. It SHALL NOT create a second config entry, and it SHALL NOT abort with `already_configured`.
#### Scenario: Reauth triggered
- **WHEN** the coordinator raises `ConfigEntryAuthFailed` because token refresh has failed
- **THEN** Home Assistant SHALL start a reauth flow for the affected entry
- **THEN** the flow SHALL show the `reauth_confirm` form pre-filled with the stored email
- **THEN** submitting credentials SHALL advance to the token step
#### Scenario: Reauth succeeds and persists new tokens
- **WHEN** the user submits a valid verification token during reauth and authentication succeeds
- **THEN** the existing config entry's access token, ID token, and refresh token SHALL be replaced with the newly issued values
- **THEN** the entry's stored email and machine ID SHALL be preserved unchanged
- **THEN** the entry SHALL be reloaded
- **THEN** the flow SHALL abort with reason `reauth_successful`
- **THEN** no additional config entry SHALL be created
#### Scenario: Reauth does not abort as already configured
- **WHEN** reauth authentication succeeds for the same account as the entry under repair
- **THEN** the flow SHALL NOT abort with reason `already_configured`
- **THEN** the "authentication failed, please re-authenticate" condition SHALL clear once the reloaded entry polls successfully
#### Scenario: Reauth with a different account is rejected
- **WHEN** the user submits credentials during reauth for an email whose lowercased value differs from the entry's unique ID, and authentication succeeds
- **THEN** the flow SHALL abort with reason `reauth_account_mismatch`
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Reauth accepts the same account in different letter case
- **WHEN** the user re-enters the entry's email with different capitalisation during reauth
- **THEN** the flow SHALL treat it as the same account and complete successfully
#### Scenario: Reauth authentication fails
- **WHEN** the verification token is expired or the credentials are wrong during reauth
- **THEN** the flow SHALL show the `invalid_auth` error on the token form and allow retry with a fresh token
- **THEN** the existing config entry's tokens SHALL be left unchanged
#### Scenario: Machine ID lookup is skipped when already known
- **WHEN** reauth authentication succeeds and the existing entry already records a machine ID
- **THEN** the flow SHALL NOT call the user profile endpoint
- **THEN** the entry SHALL retain its recorded machine ID
#### Scenario: Machine ID recovered when absent
- **WHEN** reauth authentication succeeds and the existing entry has no machine ID recorded
- **THEN** the flow SHALL fetch the user profile and store the discovered machine ID on the entry
## ADDED Requirements
### Requirement: Minimum Home Assistant core version is declared
The integration SHALL declare a minimum supported Home Assistant core version of 2024.11.0 in `hacs.json`, because the config flow depends on reauth helpers introduced in that release.
#### Scenario: Installation on an unsupported core
- **WHEN** a user attempts to install the integration through HACS on a core older than 2024.11.0
- **THEN** HACS SHALL refuse the installation and report the minimum version, rather than allowing an install that fails at runtime
### Requirement: Account mismatch abort is translated
Every abort reason the config flow can emit SHALL have a corresponding entry under `config.abort` in `strings.json` and `translations/en.json`, so no user ever sees an untranslated reason key.
#### Scenario: Mismatch message is rendered
- **WHEN** the reauth flow aborts with reason `reauth_account_mismatch`
- **THEN** the dialog SHALL render a translated message explaining that the credentials belong to a different account than the one being re-authenticated
+63
View File
@@ -0,0 +1,63 @@
## 1. Isolate the work
- [ ] 1.1 Create the agent worktree and branch: `scripts/agent-worktree.sh create fix-reauth-flow master`
- [ ] 1.2 Confirm `.agent-lock` exists in `.worktree/fix-reauth-flow` and records this task
- [ ] 1.3 Confirm the worktree base includes merge commit `3b69942` (PR #2 mirrored to both remotes)
## 2. Test harness
- [ ] 2.1 Add `requirements-test.txt` pinning `pytest-homeassistant-custom-component` to a release tracking core 2024.11 or newer, plus `pytest-asyncio` if the pin does not supply it
- [ ] 2.2 Add `tests/conftest.py` enabling custom integrations (the `auto_enable_custom_integrations` fixture) so `custom_components/perfectdraft` is loadable by the `hass` fixture
- [ ] 2.3 Install the harness into `.venv` and confirm `pytest tests/` collects
- [ ] 2.4 Confirm `python3 -m unittest discover -s tests` still passes standalone, proving `test_keg_detection.py` kept its stdlib-only imports
## 3. Failing regression tests
Write these against the current broken code first and watch them fail for the right reason — an `already_configured` abort, not an import or fixture error.
- [ ] 3.1 `tests/test_config_flow.py`: reauth with a valid token updates the existing entry's access, ID, and refresh tokens
- [ ] 3.2 Same test asserts the entry's email and machine ID are unchanged and that `hass.config_entries.async_entries(DOMAIN)` still has length 1
- [ ] 3.3 Assert the reauth flow's result type is `ABORT` with reason `reauth_successful`, and explicitly assert the reason is not `already_configured`
- [ ] 3.4 Reauth with a different account's email aborts with `reauth_account_mismatch` and leaves the stored tokens untouched
- [ ] 3.5 Reauth re-entering the same email in different capitalisation succeeds
- [ ] 3.6 Reauth with a rejected token shows the `invalid_auth` error on the token form and leaves the stored tokens untouched
- [ ] 3.7 Reauth does not call the user profile endpoint when the entry already records a machine ID
- [ ] 3.8 Reauth fetches the profile and stores the machine ID when the entry has none
- [ ] 3.9 Initial user setup still creates an entry, and a second setup with an already-configured email still aborts with `already_configured`
## 4. Implement the fix
- [ ] 4.1 Import `SOURCE_REAUTH` from `homeassistant.config_entries` in `config_flow.py`
- [ ] 4.2 In `async_step_token`, replace the unconditional `_abort_if_unique_id_configured()` + `async_create_entry()` terminal block with the source-aware branch from design Decision 1
- [ ] 4.3 On the reauth branch, call `_abort_if_unique_id_mismatch(reason="reauth_account_mismatch")` then `async_update_reload_and_abort(self._get_reauth_entry(), data_updates={...})` carrying only the three token fields
- [ ] 4.4 Make the machine ID lookup conditional: skip `get_user_profile()` when the source is reauth and `self._get_reauth_entry().data` already has `CONF_MACHINE_ID`; otherwise fetch as today and include it in the data written
- [ ] 4.5 Confirm the non-reauth branch is byte-for-byte equivalent in behaviour to today's setup path
## 5. Strings and packaging
- [ ] 5.1 Add `reauth_account_mismatch` under `config.abort` in `custom_components/perfectdraft/strings.json` with a message naming the mismatch and the two ways out (use the original account, or delete the entry and add the new one)
- [ ] 5.2 Mirror the same key and message into `custom_components/perfectdraft/translations/en.json`
- [ ] 5.3 Cross-check that every abort reason reachable from `config_flow.py` (`already_configured`, `reauth_successful`, `reauth_account_mismatch`) is present in both files
- [ ] 5.4 Add `"homeassistant": "2024.11.0"` to `hacs.json`
- [ ] 5.5 Bump `version` in `manifest.json` to `0.3.1`
- [ ] 5.6 Verify `strings.json`, `translations/en.json`, `hacs.json`, and `manifest.json` all still parse as JSON
## 6. Verify
- [ ] 6.1 All tests from section 3 pass: `pytest tests/ -v`
- [ ] 6.2 `python3 -m unittest discover -s tests` still passes (11 keg-detection tests)
- [ ] 6.3 `python3 -m compileall -q custom_components/perfectdraft/` is clean
- [ ] 6.4 On-device: install the branch on the live HA instance, forge an expired session by editing `access_token`/`refresh_token` in `config/.storage/core.config_entries`, restart, and confirm the reauth repair appears
- [ ] 6.5 On-device: complete the reauth flow with a fresh verification token and confirm it ends on "Re-authentication successful" — not "already configured"
- [ ] 6.6 On-device: confirm the integration polls successfully afterwards, entity history is continuous, and the keg-freshness baseline survived (no reset to unknown)
- [ ] 6.7 On-device: confirm entering a different account's email during reauth is rejected with the mismatch message
## 7. Close out
- [ ] 7.1 Commit on `agent/fix-reauth-flow` with a message explaining why `_abort_if_unique_id_configured` was the wrong helper for the reauth source
- [ ] 7.2 Merge into `master` from the main checkout
- [ ] 7.3 Push `master` to `origin` (git.falkvinge.net) and to `github` so both remotes stay at parity
- [ ] 7.4 Sync the delta spec into `openspec/specs/config-flow/spec.md` to reflect what was actually built
- [ ] 7.5 Archive: `mv openspec/changes/fix-reauth-flow openspec/changes/archive/<YYYY-MM-DD>-fix-reauth-flow`
- [ ] 7.6 Remove the worktree and branch: `git worktree remove .worktree/fix-reauth-flow --force && git branch -d agent/fix-reauth-flow`
- [ ] 7.7 Record the deferred item (persisting Cognito-refreshed tokens back to the config entry) as a TODO in `PROJECT_HYGIENE.md` section 11, alongside the existing pour-count TODO