Repository: home-assistant/core
Pull request #142251: Add reauth flow to bosch_alarm
Author: login: sanjay900
Labels: name: cla-signed
name: new-feature
name: has-tests
name: by-code-owner
name: quality-scale
name: Quality Scale: bronze
name: integration: bosch_alarm
Created: 2025-04-04T07:00:33Z | Merged: 2025-04-05T12:26:35Z

<!--
  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.
-->
Add a reauth flow to bosch_alarm that triggers if we get an authentication error at startup

## 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
- [ ] Bugfix (non-breaking change which fixes an issue)
- [ ] New integration (thank you!)
- [x] 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: https://github.com/home-assistant/home-assistant.io/pull/38375
- 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.
-->

- [x] The code change is tested and works locally.
- [x] Local tests pass. **Your PR cannot be merged unless tests pass**
- [x] There is no commented out code in this PR.
- [x] I have followed the [development checklist][dev-checklist]
- [x] I have followed the [perfect PR recommendations][perfect-pr]
- [x] The code has been formatted using Ruff (`ruff format homeassistant tests`)
- [x] 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/bosch_alarm/__init__.py b/homeassistant/components/bosch_alarm/__init__.py
index bc7fee46f60d9..ddd736b47c04e 100644
--- a/homeassistant/components/bosch_alarm/__init__.py
+++ b/homeassistant/components/bosch_alarm/__init__.py
@@ -9,7 +9,7 @@
 from homeassistant.config_entries import ConfigEntry
 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, Platform
 from homeassistant.core import HomeAssistant
-from homeassistant.exceptions import ConfigEntryNotReady
+from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
 from homeassistant.helpers import device_registry as dr
 
 from .const import CONF_INSTALLER_CODE, CONF_USER_CODE, DOMAIN
@@ -34,10 +34,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: BoschAlarmConfigEntry) -
         await panel.connect()
     except (PermissionError, ValueError) as err:
         await panel.disconnect()
-        raise ConfigEntryNotReady from err
+        raise ConfigEntryAuthFailed(
+            translation_domain=DOMAIN, translation_key="authentication_failed"
+        ) from err
     except (TimeoutError, OSError, ConnectionRefusedError, SSLError) as err:
         await panel.disconnect()
-        raise ConfigEntryNotReady("Connection failed") from err
+        raise ConfigEntryNotReady(
+            translation_domain=DOMAIN,
+            translation_key="cannot_connect",
+        ) from err
 
     entry.runtime_data = panel
 
diff --git a/homeassistant/components/bosch_alarm/config_flow.py b/homeassistant/components/bosch_alarm/config_flow.py
index e48f2a11944f6..4b1e3e511fc8e 100644
--- a/homeassistant/components/bosch_alarm/config_flow.py
+++ b/homeassistant/components/bosch_alarm/config_flow.py
@@ -3,6 +3,7 @@
 from __future__ import annotations
 
 import asyncio
+from collections.abc import Mapping
 import logging
 import ssl
 from typing import Any
@@ -163,3 +164,55 @@ async def async_step_auth(
             data_schema=self.add_suggested_values_to_schema(schema, user_input),
             errors=errors,
         )
+
+    async def async_step_reauth(
+        self, entry_data: Mapping[str, Any]
+    ) -> ConfigFlowResult:
+        """Perform reauth upon an authentication error."""
+        self._data = dict(entry_data)
+        return await self.async_step_reauth_confirm()
+
+    async def async_step_reauth_confirm(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the reauth step."""
+        errors: dict[str, str] = {}
+
+        # Each model variant requires a different authentication flow
+        if "Solution" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_SOLUTION
+        elif "AMAX" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_AMAX
+        else:
+            schema = STEP_AUTH_DATA_SCHEMA_BG
+
+        if user_input is not None:
+            reauth_entry = self._get_reauth_entry()
+            self._data.update(user_input)
+            try:
+                (_, _) = await try_connect(self._data, Panel.LOAD_EXTENDED_INFO)
+            except (PermissionError, ValueError) as e:
+                errors["base"] = "invalid_auth"
+                _LOGGER.error("Authentication Error: %s", e)
+            except (
+                OSError,
+                ConnectionRefusedError,
+                ssl.SSLError,
+                TimeoutError,
+            ) as e:
+                _LOGGER.error("Connection Error: %s", e)
+                errors["base"] = "cannot_connect"
+            except Exception:
+                _LOGGER.exception("Unexpected exception")
+                errors["base"] = "unknown"
+            else:
+                return self.async_update_reload_and_abort(
+                    reauth_entry,
+                    data_updates=user_input,
+                )
+
+        return self.async_show_form(
+            step_id="reauth_confirm",
+            data_schema=self.add_suggested_values_to_schema(schema, user_input),
+            errors=errors,
+        )
diff --git a/homeassistant/components/bosch_alarm/quality_scale.yaml b/homeassistant/components/bosch_alarm/quality_scale.yaml
index 467760fb863e2..75c331ede40d2 100644
--- a/homeassistant/components/bosch_alarm/quality_scale.yaml
+++ b/homeassistant/components/bosch_alarm/quality_scale.yaml
@@ -40,7 +40,7 @@ rules:
   integration-owner: done
   log-when-unavailable: todo
   parallel-updates: todo
-  reauthentication-flow: todo
+  reauthentication-flow: done
   test-coverage: done
 
   # Gold
diff --git a/homeassistant/components/bosch_alarm/strings.json b/homeassistant/components/bosch_alarm/strings.json
index f4846021b557c..3123c1697f35a 100644
--- a/homeassistant/components/bosch_alarm/strings.json
+++ b/homeassistant/components/bosch_alarm/strings.json
@@ -22,6 +22,18 @@
           "installer_code": "The installer code from your panel",
           "user_code": "The user code from your panel"
         }
+      },
+      "reauth_confirm": {
+        "data": {
+          "password": "[%key:common::config_flow::data::password%]",
+          "installer_code": "[%key:component::bosch_alarm::config::step::auth::data::installer_code%]",
+          "user_code": "[%key:component::bosch_alarm::config::step::auth::data::user_code%]"
+        },
+        "data_description": {
+          "password": "[%key:component::bosch_alarm::config::step::auth::data_description::password%]",
+          "installer_code": "[%key:component::bosch_alarm::config::step::auth::data_description::installer_code%]",
+          "user_code": "[%key:component::bosch_alarm::config::step::auth::data_description::user_code%]"
+        }
       }
     },
     "error": {
@@ -30,7 +42,16 @@
       "unknown": "[%key:common::config_flow::error::unknown%]"
     },
     "abort": {
-      "already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
+      "already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
+      "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
+    }
+  },
+  "exceptions": {
+    "cannot_connect": {
+      "message": "Could not connect to panel."
+    },
+    "authentication_failed": {
+      "message": "Incorrect credentials for panel."
     }
   }
 }
diff --git a/tests/components/bosch_alarm/test_config_flow.py b/tests/components/bosch_alarm/test_config_flow.py
index 066b3008821f5..4a1c9dad3ea91 100644
--- a/tests/components/bosch_alarm/test_config_flow.py
+++ b/tests/components/bosch_alarm/test_config_flow.py
@@ -13,6 +13,8 @@
 from homeassistant.core import HomeAssistant
 from homeassistant.data_entry_flow import FlowResultType
 
+from . import setup_integration
+
 from tests.common import MockConfigEntry
 
 
@@ -210,3 +212,74 @@ async def test_entry_already_configured_serial(
 
     assert result["type"] is FlowResultType.ABORT
     assert result["reason"] == "already_configured"
+
+
+async def test_reauth_flow_success(
+    hass: HomeAssistant,
+    mock_setup_entry: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    mock_panel: AsyncMock,
+    model_name: str,
+    serial_number: str,
+    config_flow_data: dict[str, Any],
+) -> None:
+    """Test reauth flow."""
+    await setup_integration(hass, mock_config_entry)
+    result = await mock_config_entry.start_reauth_flow(hass)
+
+    config_flow_data = {k: f"{v}2" for k, v in config_flow_data.items()}
+
+    assert result["step_id"] == "reauth_confirm"
+    # Now check it works when there are no errors
+    mock_panel.connect.side_effect = None
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["reason"] == "reauth_successful"
+    compare = {**mock_config_entry.data, **config_flow_data}
+    assert compare == mock_config_entry.data
+
+
+@pytest.mark.parametrize(
+    ("exception", "message"),
+    [
+        (OSError(), "cannot_connect"),
+        (PermissionError(), "invalid_auth"),
+        (Exception(), "unknown"),
+    ],
+)
+async def test_reauth_flow_error(
+    hass: HomeAssistant,
+    mock_setup_entry: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    mock_panel: AsyncMock,
+    model_name: str,
+    serial_number: str,
+    config_flow_data: dict[str, Any],
+    exception: Exception,
+    message: str,
+) -> None:
+    """Test reauth flow."""
+    await setup_integration(hass, mock_config_entry)
+    result = await mock_config_entry.start_reauth_flow(hass)
+
+    config_flow_data = {k: f"{v}2" for k, v in config_flow_data.items()}
+
+    assert result["step_id"] == "reauth_confirm"
+    mock_panel.connect.side_effect = exception
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["step_id"] == "reauth_confirm"
+    assert result["errors"]["base"] == message
+
+    mock_panel.connect.side_effect = None
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["reason"] == "reauth_successful"
+    compare = {**mock_config_entry.data, **config_flow_data}
+    assert compare == mock_config_entry.data
diff --git a/tests/components/bosch_alarm/test_init.py b/tests/components/bosch_alarm/test_init.py
index 0497a91eadfd0..13e938bd71114 100644
--- a/tests/components/bosch_alarm/test_init.py
+++ b/tests/components/bosch_alarm/test_init.py
@@ -20,12 +20,26 @@ def disable_platform_only():
 
 
 @pytest.mark.parametrize("model", ["solution_3000"])
-@pytest.mark.parametrize("exception", [PermissionError(), TimeoutError()])
+@pytest.mark.parametrize("exception", [PermissionError()])
 async def test_incorrect_auth(
     hass: HomeAssistant,
     mock_panel: AsyncMock,
     mock_config_entry: MockConfigEntry,
     exception: Exception,
+) -> None:
+    """Test errors with incorrect auth."""
+    mock_panel.connect.side_effect = exception
+    await setup_integration(hass, mock_config_entry)
+    assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
+
+
+@pytest.mark.parametrize("model", ["solution_3000"])
+@pytest.mark.parametrize("exception", [TimeoutError()])
+async def test_connection_error(
+    hass: HomeAssistant,
+    mock_panel: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    exception: Exception,
 ) -> None:
     """Test errors with incorrect auth."""
     mock_panel.connect.side_effect = exception


Reviews:
user: login: erwindouna
state: CHANGES_REQUESTED
author_association: MEMBER
submitted_at: 2025-04-05T09:57:47Z
user: login: joostlek
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-05T10:01:03Z
user: login: joostlek
state: CHANGES_REQUESTED
author_association: MEMBER
submitted_at: 2025-04-05T10:02:52Z
user: login: sanjay900
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-05T10:10:52Z
user: login: erwindouna
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-05T10:14:02Z
user: login: sanjay900
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-05T10:20:23Z
user: login: joostlek
state: COMMENTED
author_association: MEMBER
submitted_at: 2025-04-05T10:35:46Z
user: login: elmurato
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-04-05T11:50:57Z
user: login: joostlek
state: APPROVED
author_association: MEMBER
submitted_at: 2025-04-05T12:26:21Z

Review comments:
diff_hunk: @@ -163,3 +164,55 @@ async def async_step_auth(
             data_schema=self.add_suggested_values_to_schema(schema, user_input),
             errors=errors,
         )
+
+    async def async_step_reauth(
+        self, entry_data: Mapping[str, Any]
+    ) -> ConfigFlowResult:
+        """Perform reauth upon an authentication error."""
+        self._data = dict(entry_data)
+        return await self.async_step_reauth_confirm()
+
+    async def async_step_reauth_confirm(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the reauth step."""
+        errors: dict[str, str] = {}
+
+        # Each model variant requires a different authentication flow
+        if "Solution" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_SOLUTION
+        elif "AMAX" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_AMAX
+        else:
+            schema = STEP_AUTH_DATA_SCHEMA_BG
+
+        if user_input is not None:
+            reauth_entry = self._get_reauth_entry()
+            self._data.update(user_input)
+            try:
+                (_, _) = await try_connect(self._data, Panel.LOAD_EXTENDED_INFO)
+            except (PermissionError, ValueError) as e:
+                errors["base"] = "invalid_auth"
+                _LOGGER.error("Authentication Error: %s", e)
+            except (
+                OSError,
+                ConnectionRefusedError,
+                ssl.SSLError,
+                TimeoutError,
+            ) as e:
+                _LOGGER.error("Connection Error: %s", e)
+                errors["base"] = "cannot_connect"
+            except Exception:
+                _LOGGER.exception("Unexpected exception")
+                errors["base"] = "unknown"
+            else:
path: homeassistant/components/bosch_alarm/config_flow.py
user: login: erwindouna
body: The else is not needed here?
created_at: 2025-04-05T09:56:08Z
author_association: MEMBER
diff_hunk: @@ -163,3 +164,55 @@ async def async_step_auth(
             data_schema=self.add_suggested_values_to_schema(schema, user_input),
             errors=errors,
         )
+
+    async def async_step_reauth(
+        self, entry_data: Mapping[str, Any]
+    ) -> ConfigFlowResult:
+        """Perform reauth upon an authentication error."""
+        self._data = dict(entry_data)
+        return await self.async_step_reauth_confirm()
+
+    async def async_step_reauth_confirm(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the reauth step."""
+        errors: dict[str, str] = {}
+
+        # Each model variant requires a different authentication flow
+        if "Solution" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_SOLUTION
+        elif "AMAX" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_AMAX
+        else:
+            schema = STEP_AUTH_DATA_SCHEMA_BG
+
+        if user_input is not None:
+            reauth_entry = self._get_reauth_entry()
+            self._data.update(user_input)
+            try:
+                (_, _) = await try_connect(self._data, Panel.LOAD_EXTENDED_INFO)
+            except (PermissionError, ValueError) as e:
+                errors["base"] = "invalid_auth"
+                _LOGGER.error("Authentication Error: %s", e)
+            except (
+                OSError,
+                ConnectionRefusedError,
+                ssl.SSLError,
+                TimeoutError,
+            ) as e:
+                _LOGGER.error("Connection Error: %s", e)
+                errors["base"] = "cannot_connect"
+            except Exception:
+                _LOGGER.exception("Unexpected exception")
+                errors["base"] = "unknown"
+            else:
path: homeassistant/components/bosch_alarm/config_flow.py
user: login: joostlek
body: It is, because this is called when we didn't end up in an except block
created_at: 2025-04-05T10:01:03Z
author_association: MEMBER
diff_hunk: @@ -22,6 +22,18 @@
           "installer_code": "The installer code from your panel",
           "user_code": "The user code from your panel"
         }
+      },
+      "reauth_confirm": {
+        "data": {
+          "password": "[%key:common::config_flow::data::password%]",
+          "installer_code": "Installer code",
+          "user_code": "User code"
+        },
+        "data_description": {
+          "password": "The Mode 2 automation code from your panel",
+          "installer_code": "The installer code from your panel",
+          "user_code": "The user code from your panel"
+        }
path: homeassistant/components/bosch_alarm/strings.json
user: login: joostlek
body: We can use references to the already present strings
created_at: 2025-04-05T10:01:36Z
author_association: MEMBER
diff_hunk: @@ -210,3 +212,54 @@ async def test_entry_already_configured_serial(
 
     assert result["type"] is FlowResultType.ABORT
     assert result["reason"] == "already_configured"
+
+
+async def test_reauth_flow(
+    hass: HomeAssistant,
+    mock_setup_entry: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    mock_panel: AsyncMock,
+    model_name: str,
+    serial_number: str,
+    config_flow_data: dict[str, Any],
+) -> None:
+    """Test reauth flow."""
+    await setup_integration(hass, mock_config_entry)
+    result = await mock_config_entry.start_reauth_flow(hass)
+
+    config_flow_data = {k: f"{v}2" for k, v in config_flow_data.items()}
+
+    assert result["step_id"] == "reauth_confirm"
+    # Check if reauth fails if the alarm returns a permission error
+    mock_panel.connect.side_effect = PermissionError()
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["step_id"] == "reauth_confirm"
+    assert result["errors"]["base"] == "invalid_auth"
+    # Check if reauth fails if the alarm returns a connection error
+    mock_panel.connect.side_effect = OSError()
path: tests/components/bosch_alarm/test_config_flow.py
user: login: joostlek
body: I would rather see the not happy flow in a different test than it being included in the happy flow test
created_at: 2025-04-05T10:02:35Z
author_association: MEMBER
diff_hunk: @@ -22,6 +22,18 @@
           "installer_code": "The installer code from your panel",
           "user_code": "The user code from your panel"
         }
+      },
+      "reauth_confirm": {
+        "data": {
+          "password": "[%key:common::config_flow::data::password%]",
+          "installer_code": "Installer code",
+          "user_code": "User code"
+        },
+        "data_description": {
+          "password": "The Mode 2 automation code from your panel",
+          "installer_code": "The installer code from your panel",
+          "user_code": "The user code from your panel"
+        }
path: homeassistant/components/bosch_alarm/strings.json
user: login: sanjay900
body: whats the proper syntax for that?
created_at: 2025-04-05T10:10:52Z
author_association: CONTRIBUTOR
diff_hunk: @@ -163,3 +164,55 @@ async def async_step_auth(
             data_schema=self.add_suggested_values_to_schema(schema, user_input),
             errors=errors,
         )
+
+    async def async_step_reauth(
+        self, entry_data: Mapping[str, Any]
+    ) -> ConfigFlowResult:
+        """Perform reauth upon an authentication error."""
+        self._data = dict(entry_data)
+        return await self.async_step_reauth_confirm()
+
+    async def async_step_reauth_confirm(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the reauth step."""
+        errors: dict[str, str] = {}
+
+        # Each model variant requires a different authentication flow
+        if "Solution" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_SOLUTION
+        elif "AMAX" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_AMAX
+        else:
+            schema = STEP_AUTH_DATA_SCHEMA_BG
+
+        if user_input is not None:
+            reauth_entry = self._get_reauth_entry()
+            self._data.update(user_input)
+            try:
+                (_, _) = await try_connect(self._data, Panel.LOAD_EXTENDED_INFO)
+            except (PermissionError, ValueError) as e:
+                errors["base"] = "invalid_auth"
+                _LOGGER.error("Authentication Error: %s", e)
+            except (
+                OSError,
+                ConnectionRefusedError,
+                ssl.SSLError,
+                TimeoutError,
+            ) as e:
+                _LOGGER.error("Connection Error: %s", e)
+                errors["base"] = "cannot_connect"
+            except Exception:
+                _LOGGER.exception("Unexpected exception")
+                errors["base"] = "unknown"
+            else:
path: homeassistant/components/bosch_alarm/config_flow.py
user: login: erwindouna
body: It would normally run through?
created_at: 2025-04-05T10:14:02Z
author_association: MEMBER
diff_hunk: @@ -163,3 +164,55 @@ async def async_step_auth(
             data_schema=self.add_suggested_values_to_schema(schema, user_input),
             errors=errors,
         )
+
+    async def async_step_reauth(
+        self, entry_data: Mapping[str, Any]
+    ) -> ConfigFlowResult:
+        """Perform reauth upon an authentication error."""
+        self._data = dict(entry_data)
+        return await self.async_step_reauth_confirm()
+
+    async def async_step_reauth_confirm(
+        self, user_input: dict[str, Any] | None = None
+    ) -> ConfigFlowResult:
+        """Handle the reauth step."""
+        errors: dict[str, str] = {}
+
+        # Each model variant requires a different authentication flow
+        if "Solution" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_SOLUTION
+        elif "AMAX" in self._data[CONF_MODEL]:
+            schema = STEP_AUTH_DATA_SCHEMA_AMAX
+        else:
+            schema = STEP_AUTH_DATA_SCHEMA_BG
+
+        if user_input is not None:
+            reauth_entry = self._get_reauth_entry()
+            self._data.update(user_input)
+            try:
+                (_, _) = await try_connect(self._data, Panel.LOAD_EXTENDED_INFO)
+            except (PermissionError, ValueError) as e:
+                errors["base"] = "invalid_auth"
+                _LOGGER.error("Authentication Error: %s", e)
+            except (
+                OSError,
+                ConnectionRefusedError,
+                ssl.SSLError,
+                TimeoutError,
+            ) as e:
+                _LOGGER.error("Connection Error: %s", e)
+                errors["base"] = "cannot_connect"
+            except Exception:
+                _LOGGER.exception("Unexpected exception")
+                errors["base"] = "unknown"
+            else:
path: homeassistant/components/bosch_alarm/config_flow.py
user: login: sanjay900
body: we don't want it happening if there was an error though, hence the need for the else
created_at: 2025-04-05T10:20:23Z
author_association: CONTRIBUTOR
diff_hunk: @@ -210,3 +212,65 @@ async def test_entry_already_configured_serial(
 
     assert result["type"] is FlowResultType.ABORT
     assert result["reason"] == "already_configured"
+
+
+async def test_reauth_flow_success(
+    hass: HomeAssistant,
+    mock_setup_entry: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    mock_panel: AsyncMock,
+    model_name: str,
+    serial_number: str,
+    config_flow_data: dict[str, Any],
+) -> None:
+    """Test reauth flow."""
+    await setup_integration(hass, mock_config_entry)
+    result = await mock_config_entry.start_reauth_flow(hass)
+
+    config_flow_data = {k: f"{v}2" for k, v in config_flow_data.items()}
+
+    assert result["step_id"] == "reauth_confirm"
+    # Now check it works when there are no errors
+    mock_panel.connect.side_effect = None
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["reason"] == "reauth_successful"
+    compare = {**mock_config_entry.data, **config_flow_data}
+    assert compare == mock_config_entry.data
+
+
+@pytest.mark.parametrize(
+    ("exception", "message"),
+    [
+        (OSError(), "cannot_connect"),
+        (PermissionError(), "invalid_auth"),
+        (Exception(), "unknown"),
+    ],
+)
+async def test_reauth_flow_error(
+    hass: HomeAssistant,
+    mock_setup_entry: AsyncMock,
+    mock_config_entry: MockConfigEntry,
+    mock_panel: AsyncMock,
+    model_name: str,
+    serial_number: str,
+    config_flow_data: dict[str, Any],
+    exception: Exception,
+    message: str,
+) -> None:
+    """Test reauth flow."""
+    await setup_integration(hass, mock_config_entry)
+    result = await mock_config_entry.start_reauth_flow(hass)
+
+    config_flow_data = {k: f"{v}2" for k, v in config_flow_data.items()}
+
+    assert result["step_id"] == "reauth_confirm"
+    mock_panel.connect.side_effect = exception
+    result = await hass.config_entries.flow.async_configure(
+        result["flow_id"],
+        user_input=config_flow_data,
+    )
+    assert result["step_id"] == "reauth_confirm"
+    assert result["errors"]["base"] == message
path: tests/components/bosch_alarm/test_config_flow.py
user: login: joostlek
body: Let's finish this test so we also test that this is able to recover
created_at: 2025-04-05T10:35:42Z
author_association: MEMBER
diff_hunk: @@ -22,6 +22,18 @@
           "installer_code": "The installer code from your panel",
           "user_code": "The user code from your panel"
         }
+      },
+      "reauth_confirm": {
+        "data": {
+          "password": "[%key:common::config_flow::data::password%]",
+          "installer_code": "Installer code",
+          "user_code": "User code"
+        },
+        "data_description": {
+          "password": "The Mode 2 automation code from your panel",
+          "installer_code": "The installer code from your panel",
+          "user_code": "The user code from your panel"
+        }
path: homeassistant/components/bosch_alarm/strings.json
user: login: elmurato
body: Example:
`"[%key:component::bosch_alarm::config::step::auth::data_description::password%]"`
created_at: 2025-04-05T11:50:57Z
author_association: CONTRIBUTOR

PR comments:
user: login: home-assistant[bot]
created_at: 2025-04-04T07:00:39Z
body: 
Hey there @mag1024, mind taking a look at this pull request as it has been labeled with an integration (`bosch_alarm`) you are listed as a [code owner](https://github.com/home-assistant/core/blob/dev/CODEOWNERS#L219) for? Thanks!

<details>
<summary>Code owner commands</summary>


Code owners of `bosch_alarm` can trigger bot actions by commenting:

- `@home-assistant close` Closes the pull request.
- `@home-assistant rename Awesome new title` Renames the pull request.
- `@home-assistant reopen` Reopen the pull request.
- `@home-assistant unassign bosch_alarm` Removes the current integration label and assignees on the pull request, add the integration domain after the command.
- `@home-assistant add-label needs-more-information` Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
- `@home-assistant remove-label needs-more-information` Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

</details>


author_association: CONTRIBUTOR
user: login: home-assistant[bot]
created_at: 2025-04-05T10:02:55Z
body: <!-- ReviewDrafterComment -->
Please take a look at the requested changes, and use the **Ready for review** button when you are done, thanks :+1:

[_Learn more about our pull request process._](https://developers.home-assistant.io/docs/review-process#prs-are-being-drafted-when-changes-are-needed)

author_association: CONTRIBUTOR