Repository: home-assistant/core
Pull request #140931: Abort reauth flows on config entry reload
Author: login: emontnemery
Labels: name: core
name: cla-signed
name: bugfix
Created: 2025-03-19T13:42:23Z | Merged: 2025-04-10T18:55:34Z

<!--
  You are amazing! Thanks for contributing to our project!
  Please, DO NOT DELETE ANY TEXT from this template! (unless instructed).
-->
## Proposed change
<!--
  Describe the big picture of your changes here to communicate to the
  maintainers why we should accept this pull request. If it fixes a bug
  or resolves a feature request, be sure to link to that issue in the
  additional information section.
-->
Abort reauth flows on config entry reload

Background here: https://github.com/home-assistant/core/pull/140723#issuecomment-2728284713

~~Needs https://github.com/home-assistant/core/pull/142079~~

## Type of change
<!--
  What type of change does your PR introduce to Home Assistant?
  NOTE: Please, check only 1! box!
  If your PR requires multiple boxes to be checked, you'll most likely need to
  split it into multiple PRs. This makes things easier and faster to code review.
-->

- [ ] Dependency upgrade
- [x] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [ ] New feature (which adds functionality to an existing integration)
- [ ] Deprecation (breaking change to happen in the future)
- [ ] Breaking change (fix/feature causing existing functionality to break)
- [ ] Code quality improvements to existing code or addition of tests

## Additional information
<!--
  Details are important, and help maintainers processing your PR.
  Please be sure to fill out additional details, if applicable.
-->

- This PR fixes or closes issue: fixes #
- This PR is related to issue: 
- Link to documentation pull request: 
- Link to developer documentation pull request: 
- Link to frontend pull request: 

## Checklist
<!--
  Put an `x` in the boxes that apply. You can also fill these out after
  creating the PR. If you're unsure about any of them, don't hesitate to ask.
  We're here to help! This is simply a reminder of what we are going to look
  for before merging your code.
-->

- [ ] The code change is tested and works locally.
- [ ] Local tests pass. **Your PR cannot be merged unless tests pass**
- [ ] There is no commented out code in this PR.
- [ ] I have followed the [development checklist][dev-checklist]
- [ ] I have followed the [perfect PR recommendations][perfect-pr]
- [ ] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [ ] Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

- [ ] Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

- [ ] The [manifest file][manifest-docs] has all fields filled out correctly.  
      Updated and included derived files by running: `python3 -m script.hassfest`.
- [ ] New or updated dependencies have been added to `requirements_all.txt`.  
      Updated by running `python3 -m script.gen_requirements_all`.
- [ ] For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

<!--
  This project is very active and we have a high turnover of pull requests.

  Unfortunately, the number of incoming pull requests is higher than what our
  reviewers can review and merge so there is a long backlog of pull requests
  waiting for review. You can help here!
  
  By reviewing another pull request, you will help raise the code quality of
  that pull request and the final review will be faster. This way the general
  pace of pull request reviews will go up and your wait time will go down.
  
  When picking a pull request to review, try to choose one that hasn't yet
  been reviewed.

  Thanks for helping out!
-->

To help with the load of incoming pull requests:

- [ ] I have reviewed two other [open pull requests][prs] in this repository.

[prs]: https://github.com/home-assistant/core/pulls?q=is%3Aopen+is%3Apr+-author%3A%40me+-draft%3Atrue+-label%3Awaiting-for-upstream+sort%3Acreated-desc+review%3Anone+-status%3Afailure

<!--
  Thank you for contributing <3

  Below, some useful links you could explore:
-->
[dev-checklist]: https://developers.home-assistant.io/docs/development_checklist/
[manifest-docs]: https://developers.home-assistant.io/docs/creating_integration_manifest/
[quality-scale]: https://developers.home-assistant.io/docs/integration_quality_scale_index/
[docs-repository]: https://github.com/home-assistant/home-assistant.io
[perfect-pr]: https://developers.home-assistant.io/docs/review-process/#creating-the-perfect-pr



Diff:
diff --git a/homeassistant/components/tplink/config_flow.py b/homeassistant/components/tplink/config_flow.py
index 291a7e78c626c..0914c4191cf57 100644
--- a/homeassistant/components/tplink/config_flow.py
+++ b/homeassistant/components/tplink/config_flow.py
@@ -567,7 +567,7 @@ async def async_step_pick_device(
         )
 
     async def _async_reload_requires_auth_entries(self) -> None:
-        """Reload any in progress config flow that now have credentials."""
+        """Reload all config entries after auth update."""
         _config_entries = self.hass.config_entries
 
         if self.source == SOURCE_REAUTH:
@@ -579,11 +579,9 @@ async def _async_reload_requires_auth_entries(self) -> None:
             context = flow["context"]
             if context.get("source") != SOURCE_REAUTH:
                 continue
-            entry_id: str = context["entry_id"]
+            entry_id = context["entry_id"]
             if entry := _config_entries.async_get_entry(entry_id):
                 await _config_entries.async_reload(entry.entry_id)
-                if entry.state is ConfigEntryState.LOADED:
-                    _config_entries.flow.async_abort(flow["flow_id"])
 
     @callback
     def _async_create_or_update_entry_from_device(
diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py
index 705cc01061bb5..dadd4b8b8a33a 100644
--- a/homeassistant/config_entries.py
+++ b/homeassistant/config_entries.py
@@ -1513,10 +1513,9 @@ def async_flow_removed(
 
         # Clean up issue if this is a reauth flow
         if flow.context["source"] == SOURCE_REAUTH:
-            if (entry_id := flow.context.get("entry_id")) is not None and (
-                entry := self.config_entries.async_get_entry(entry_id)
-            ) is not None:
-                issue_id = f"config_entry_reauth_{entry.domain}_{entry.entry_id}"
+            if (entry_id := flow.context.get("entry_id")) is not None:
+                # The config entry's domain is flow.handler
+                issue_id = f"config_entry_reauth_{flow.handler}_{entry_id}"
                 ir.async_delete_issue(self.hass, HOMEASSISTANT_DOMAIN, issue_id)
 
     async def async_finish_flow(
@@ -2097,13 +2096,7 @@ def _async_clean_up(self, entry: ConfigEntry) -> None:
         # If the configuration entry is removed during reauth, it should
         # abort any reauth flow that is active for the removed entry and
         # linked issues.
-        for progress_flow in self.hass.config_entries.flow.async_progress_by_handler(
-            entry.domain, match_context={"entry_id": entry_id, "source": SOURCE_REAUTH}
-        ):
-            if "flow_id" in progress_flow:
-                self.hass.config_entries.flow.async_abort(progress_flow["flow_id"])
-                issue_id = f"config_entry_reauth_{entry.domain}_{entry.entry_id}"
-                ir.async_delete_issue(self.hass, HOMEASSISTANT_DOMAIN, issue_id)
+        _abort_reauth_flows(self.hass, entry.domain, entry_id)
 
         self._async_dispatch(ConfigEntryChange.REMOVED, entry)
 
@@ -2235,6 +2228,9 @@ async def async_reload(self, entry_id: str) -> bool:
         # attempts.
         entry.async_cancel_retry_setup()
 
+        # Abort any in-progress reauth flow and linked issues
+        _abort_reauth_flows(self.hass, entry.domain, entry_id)
+
         if entry.domain not in self.hass.config.components:
             # If the component is not loaded, just load it as
             # the config entry will be loaded as well. We need
@@ -3766,3 +3762,13 @@ async def _async_get_flow_handler(
         return handler
 
     raise data_entry_flow.UnknownHandler
+
+
+@callback
+def _abort_reauth_flows(hass: HomeAssistant, domain: str, entry_id: str) -> None:
+    """Abort reauth flows for an entry."""
+    for progress_flow in hass.config_entries.flow.async_progress_by_handler(
+        domain, match_context={"entry_id": entry_id, "source": SOURCE_REAUTH}
+    ):
+        if "flow_id" in progress_flow:
+            hass.config_entries.flow.async_abort(progress_flow["flow_id"])
diff --git a/homeassistant/data_entry_flow.py b/homeassistant/data_entry_flow.py
index 6a288380cd063..e2e31ffce2982 100644
--- a/homeassistant/data_entry_flow.py
+++ b/homeassistant/data_entry_flow.py
@@ -494,8 +494,11 @@ async def _async_handle_step(
             )
 
         if flow.flow_id not in self._progress:
-            # The flow was removed during the step
-            raise UnknownFlow
+            # The flow was removed during the step, raise UnknownFlow
+            # unless the result is an abort
+            if result["type"] != FlowResultType.ABORT:
+                raise UnknownFlow
+            return result
 
         # Setup the flow handler's preview if needed
         if result.get("preview") is not None:
@@ -547,7 +550,7 @@ def schedule_configure(_: asyncio.Task) -> None:
             flow.cur_step = result
             return result
 
-        # Abort and Success results both finish the flow
+        # Abort and Success results both finish the flow.
         self._async_remove_flow_progress(flow.flow_id)
 
         return result
diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py
index 5c2e2aea21509..e07621e381d5f 100644
--- a/tests/test_config_entries.py
+++ b/tests/test_config_entries.py
@@ -695,7 +695,7 @@ async def test_remove_entry_cancels_reauth(
     manager: config_entries.ConfigEntries,
     issue_registry: ir.IssueRegistry,
 ) -> None:
-    """Tests that removing a config entry, also aborts existing reauth flows."""
+    """Tests that removing a config entry also aborts existing reauth flows."""
     entry = MockConfigEntry(title="test_title", domain="test")
 
     mock_setup_entry = AsyncMock(side_effect=ConfigEntryAuthFailed())
@@ -722,6 +722,40 @@ async def test_remove_entry_cancels_reauth(
     assert not issue_registry.async_get_issue(HOMEASSISTANT_DOMAIN, issue_id)
 
 
+async def test_reload_entry_cancels_reauth(
+    hass: HomeAssistant,
+    manager: config_entries.ConfigEntries,
+    issue_registry: ir.IssueRegistry,
+) -> None:
+    """Tests that reloading a config entry also aborts existing reauth flows."""
+    entry = MockConfigEntry(title="test_title", domain="test")
+
+    mock_setup_entry = AsyncMock(side_effect=ConfigEntryAuthFailed())
+    mock_integration(hass, MockModule("test", async_setup_entry=mock_setup_entry))
+    mock_platform(hass, "test.config_flow", None)
+
+    entry.add_to_hass(hass)
+    await manager.async_setup(entry.entry_id)
+    await hass.async_block_till_done()
+
+    flows = hass.config_entries.flow.async_progress_by_handler("test")
+    assert len(flows) == 1
+    assert flows[0]["context"]["entry_id"] == entry.entry_id
+    assert flows[0]["context"]["source"] == config_entries.SOURCE_REAUTH
+    assert entry.state is config_entries.ConfigEntryState.SETUP_ERROR
+
+    issue_id = f"config_entry_reauth_test_{entry.entry_id}"
+    assert issue_registry.async_get_issue(HOMEASSISTANT_DOMAIN, issue_id)
+
+    mock_setup_entry.return_value = True
+    mock_setup_entry.side_effect = None
+    await manager.async_reload(entry.entry_id)
+
+    flows = hass.config_entries.flow.async_progress_by_handler("test")
+    assert len(flows) == 0
+    assert not issue_registry.async_get_issue(HOMEASSISTANT_DOMAIN, issue_id)
+
+
 async def test_remove_entry_handles_callback_error(
     hass: HomeAssistant, manager: config_entries.ConfigEntries
 ) -> None:
diff --git a/tests/test_data_entry_flow.py b/tests/test_data_entry_flow.py
index bcc40251bad31..804b1fea4053e 100644
--- a/tests/test_data_entry_flow.py
+++ b/tests/test_data_entry_flow.py
@@ -219,8 +219,8 @@ async def async_step_init(self, user_input=None):
             manager.async_abort(self.flow_id)
             return self.async_abort(reason="blah")
 
-    with pytest.raises(data_entry_flow.UnknownFlow):
-        await manager.async_init("test")
+    form = await manager.async_init("test")
+    assert form["reason"] == "blah"
     assert len(manager.async_progress()) == 0
     assert len(manager.mock_created_entries) == 0
 


Reviews:
user: login: emontnemery
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-25T08:42:00Z
user: login: bdraco
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-03-25T17:23:27Z
user: login: emontnemery
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-02T14:56:41Z
user: login: bdraco
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-02T20:07:27Z
user: login: bdraco
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-02T20:08:23Z
user: login: emontnemery
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-03T05:42:43Z
user: login: bdraco
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-03T06:09:22Z
user: login: bdraco
state: APPROVED
author_association: MEMBER
submitted_at: 2025-04-09T19:00:27Z

Review comments:
diff_hunk: @@ -547,8 +547,10 @@ def schedule_configure(_: asyncio.Task) -> None:
             flow.cur_step = result
             return result
 
-        # Abort and Success results both finish the flow
-        self._async_remove_flow_progress(flow.flow_id)
+        # Abort and Success results both finish the flow.
+        # Suppress UnknownFlow in case the flow is already aborted
+        with suppress(UnknownFlow):
+            self._async_remove_flow_progress(flow.flow_id)
path: homeassistant/data_entry_flow.py
user: login: emontnemery
body: We should cover this changed behavior in a test
created_at: 2025-03-25T08:42:00Z
author_association: CONTRIBUTOR
diff_hunk: @@ -3827,3 +3825,20 @@ async def _async_get_flow_handler(
         return handler
 
     raise data_entry_flow.UnknownHandler
+
+
+@callback
+def _abort_reauth_flows(hass: HomeAssistant, domain: str, entry_id: str) -> None:
+    """Abort reauth flows for an entry."""
+    for progress_flow in hass.config_entries.flow.async_progress_by_handler(
+        domain, match_context={"entry_id": entry_id, "source": SOURCE_REAUTH}
+    ):
path: homeassistant/config_entries.py
user: login: bdraco
body: Nice that this avoids the malloc/dealloc churn here by passing match_context
created_at: 2025-03-25T17:23:27Z
author_association: MEMBER
diff_hunk: @@ -217,6 +232,28 @@ async def async_step_init(self, user_input=None):
     assert entry["source"] is None
 
 
+async def test_create_aborted_flow(manager: MockFlowManager) -> None:
+    """Test return create_entry from aborted flow."""
+
+    @manager.mock_reg_handler("test")
+    class TestFlow(data_entry_flow.FlowHandler):
+        VERSION = 5
+
+        async def async_step_init(self, user_input=None):
+            manager.async_abort(self.flow_id)
+            return self.async_create_entry(title="Test Title", data="Test Data")
+
+    await manager.async_init("test")
+    assert len(manager.async_progress()) == 0
+    assert len(manager.mock_created_entries) == 1
+
+    entry = manager.mock_created_entries[0]
+    assert entry["handler"] == "test"
+    assert entry["title"] == "Test Title"
+    assert entry["data"] == "Test Data"
+    assert entry["source"] is None
path: tests/test_data_entry_flow.py
user: login: emontnemery
body: Maybe it's weird this is allowed, and we should not allow returning `create_entry` from an aborted flow?
created_at: 2025-04-02T14:56:41Z
author_association: CONTRIBUTOR
diff_hunk: @@ -217,6 +232,28 @@ async def async_step_init(self, user_input=None):
     assert entry["source"] is None
 
 
+async def test_create_aborted_flow(manager: MockFlowManager) -> None:
+    """Test return create_entry from aborted flow."""
+
+    @manager.mock_reg_handler("test")
+    class TestFlow(data_entry_flow.FlowHandler):
+        VERSION = 5
+
+        async def async_step_init(self, user_input=None):
+            manager.async_abort(self.flow_id)
+            return self.async_create_entry(title="Test Title", data="Test Data")
+
+    await manager.async_init("test")
+    assert len(manager.async_progress()) == 0
+    assert len(manager.mock_created_entries) == 1
+
+    entry = manager.mock_created_entries[0]
+    assert entry["handler"] == "test"
+    assert entry["title"] == "Test Title"
+    assert entry["data"] == "Test Data"
+    assert entry["source"] is None
path: tests/test_data_entry_flow.py
user: login: bdraco
body: That is weird...
created_at: 2025-04-02T20:07:27Z
author_association: MEMBER
diff_hunk: @@ -217,6 +232,28 @@ async def async_step_init(self, user_input=None):
     assert entry["source"] is None
 
 
+async def test_create_aborted_flow(manager: MockFlowManager) -> None:
+    """Test return create_entry from aborted flow."""
+
+    @manager.mock_reg_handler("test")
+    class TestFlow(data_entry_flow.FlowHandler):
+        VERSION = 5
+
+        async def async_step_init(self, user_input=None):
+            manager.async_abort(self.flow_id)
+            return self.async_create_entry(title="Test Title", data="Test Data")
+
+    await manager.async_init("test")
+    assert len(manager.async_progress()) == 0
+    assert len(manager.mock_created_entries) == 1
+
+    entry = manager.mock_created_entries[0]
+    assert entry["handler"] == "test"
+    assert entry["title"] == "Test Title"
+    assert entry["data"] == "Test Data"
+    assert entry["source"] is None
path: tests/test_data_entry_flow.py
user: login: bdraco
body: I can't think of a reason to allow creating entry from an aborted flow
created_at: 2025-04-02T20:08:23Z
author_association: MEMBER
diff_hunk: @@ -217,6 +232,31 @@ async def async_step_init(self, user_input=None):
     assert entry["source"] is None
 
 
+async def test_create_aborted_flow(manager: MockFlowManager) -> None:
+    """Test return create_entry from aborted flow."""
+
+    @manager.mock_reg_handler("test")
+    class TestFlow(data_entry_flow.FlowHandler):
+        VERSION = 5
+
+        async def async_step_init(self, user_input=None):
+            manager.async_abort(self.flow_id)
+            return self.async_create_entry(title="Test Title", data="Test Data")
+
+    with pytest.raises(data_entry_flow.UnknownFlow):
+        await manager.async_init("test")
+    assert len(manager.async_progress()) == 0
+
+    # The entry is created even if the flow is aborted
+    assert len(manager.mock_created_entries) == 1
+
+    entry = manager.mock_created_entries[0]
+    assert entry["handler"] == "test"
+    assert entry["title"] == "Test Title"
+    assert entry["data"] == "Test Data"
+    assert entry["source"] is None
path: tests/test_data_entry_flow.py
user: login: emontnemery
body: The behavior is quite illogical; an entry is created without checking if the flow still exists, but there's then an error.
The behavior is not changed by this PR, but I think we should look into changing it in a follow-up.
created_at: 2025-04-03T05:42:43Z
author_association: CONTRIBUTOR
diff_hunk: @@ -217,6 +232,31 @@ async def async_step_init(self, user_input=None):
     assert entry["source"] is None
 
 
+async def test_create_aborted_flow(manager: MockFlowManager) -> None:
+    """Test return create_entry from aborted flow."""
+
+    @manager.mock_reg_handler("test")
+    class TestFlow(data_entry_flow.FlowHandler):
+        VERSION = 5
+
+        async def async_step_init(self, user_input=None):
+            manager.async_abort(self.flow_id)
+            return self.async_create_entry(title="Test Title", data="Test Data")
+
+    with pytest.raises(data_entry_flow.UnknownFlow):
+        await manager.async_init("test")
+    assert len(manager.async_progress()) == 0
+
+    # The entry is created even if the flow is aborted
+    assert len(manager.mock_created_entries) == 1
+
+    entry = manager.mock_created_entries[0]
+    assert entry["handler"] == "test"
+    assert entry["title"] == "Test Title"
+    assert entry["data"] == "Test Data"
+    assert entry["source"] is None
path: tests/test_data_entry_flow.py
user: login: bdraco
body: Would you please add a comment to this test explaining that.
created_at: 2025-04-03T06:09:22Z
author_association: MEMBER

PR comments:
user: login: emontnemery
created_at: 2025-03-19T15:30:34Z
body: Tests fail because the reauth flow is now aborted early when reauth calls `async_update_reload_and_abort`
author_association: CONTRIBUTOR
user: login: emontnemery
created_at: 2025-03-20T15:25:44Z
body: ~~TODO: Add a test to assert we don't cancel reauth when reload is triggered by a reauth flow~~

This is no longer relevant
author_association: CONTRIBUTOR
user: login: bdraco
created_at: 2025-04-03T06:32:40Z
body: Looks good.  Let me put it on production and test as well
author_association: MEMBER
user: login: bdraco
created_at: 2025-04-03T06:49:25Z
body: Core works as expected but the frontend doesn't handle this well

once its reloaded the flow in the ui is still pointing to the old flow
so when you click it it errors

![reconfig](https://github.com/user-attachments/assets/557e5973-e720-4abf-8ea8-e20f49d7e9b9)

author_association: MEMBER
user: login: emontnemery
created_at: 2025-04-03T07:05:41Z
body: > Core works as expected but the frontend doesn't handle this well
> 
> once its reloaded the flow in the ui is still pointing to the old flow so when you click it it errors
> 
The bug is that frontend is not updated when the reauth flow is aborted on reload.

This shows the same behavior with `kitchen_sink`

https://github.com/user-attachments/assets/a18eb717-6862-4224-a37e-e67be790e026




author_association: CONTRIBUTOR
user: login: emontnemery
created_at: 2025-04-09T13:33:16Z
body: This PR can be simplified a bit when https://github.com/home-assistant/core/pull/142138 is merged.
I suggest we merge that PR first.
author_association: CONTRIBUTOR
user: login: emontnemery
created_at: 2025-04-09T19:00:01Z
body: The frontend issue should be fixed by https://github.com/home-assistant/frontend/pull/24985
author_association: CONTRIBUTOR