From bd38ea70fca293c5ffe0a7548ce39b59bdf664bc Mon Sep 17 00:00:00 2001 From: Hamish Date: Thu, 27 Aug 2026 03:42:21 +0930 Subject: [PATCH] Add authentication support to Gatus integration (#178663) --- homeassistant/components/gatus/config_flow.py | 115 +++++++++++++- homeassistant/components/gatus/coordinator.py | 14 +- .../components/gatus/quality_scale.yaml | 4 +- homeassistant/components/gatus/strings.json | 37 ++++- tests/components/gatus/test_config_flow.py | 143 +++++++++++++++++- tests/components/gatus/test_init.py | 17 ++- 6 files changed, 314 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/gatus/config_flow.py b/homeassistant/components/gatus/config_flow.py index 63c895bd7237..926a4ee2f3ed 100644 --- a/homeassistant/components/gatus/config_flow.py +++ b/homeassistant/components/gatus/config_flow.py @@ -1,14 +1,15 @@ """Config flow for the Gatus integration.""" +from collections.abc import Mapping import logging from typing import Any, override -from gatus_api import GatusClient, GatusClientError +from gatus_api import GatusAuthError, GatusClient, GatusClientError import voluptuous as vol from yarl import URL from homeassistant.config_entries import ConfigFlow, ConfigFlowResult -from homeassistant.const import CONF_URL +from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_URL, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession @@ -30,16 +31,44 @@ STEP_USER_DATA_SCHEMA = vol.Schema( autocomplete="url", ), ), + vol.Optional(CONF_USERNAME): TextSelector( + TextSelectorConfig( + type=TextSelectorType.TEXT, + autocomplete="username", + ), + ), + vol.Optional(CONF_PASSWORD): TextSelector( + TextSelectorConfig( + type=TextSelectorType.PASSWORD, + autocomplete="current-password", + ), + ), + vol.Optional(CONF_TOKEN): TextSelector( + TextSelectorConfig( + type=TextSelectorType.PASSWORD, + ), + ), } ) async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None: """Validate that the user input allows us to connect to Gatus and return data.""" - client = GatusClient(url=data[CONF_URL], session=async_get_clientsession(hass)) + client = GatusClient( + url=data[CONF_URL], + session=async_get_clientsession(hass), + username=data.get(CONF_USERNAME), + password=data.get(CONF_PASSWORD), + token=data.get(CONF_TOKEN), + ) try: await client.get_endpoints_statuses() + except GatusAuthError as err: + _LOGGER.debug( + "Authentication failed for Gatus instance at %s: %s", data[CONF_URL], err + ) + raise InvalidAuth from err except GatusClientError as err: _LOGGER.debug("Cannot connect to Gatus instance at %s: %s", data[CONF_URL], err) raise CannotConnect from err @@ -71,6 +100,8 @@ class GatusConfigFlow(ConfigFlow, domain=DOMAIN): await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception during Gatus setup") errors["base"] = "unknown" @@ -109,6 +140,8 @@ class GatusConfigFlow(ConfigFlow, domain=DOMAIN): await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception during Gatus reconfigure") errors["base"] = "unknown" @@ -118,14 +151,88 @@ class GatusConfigFlow(ConfigFlow, domain=DOMAIN): data_updates=user_input, ) + suggested_values = { + key: val + for key, val in (user_input or reconfigure_entry.data).items() + if key not in (CONF_PASSWORD, CONF_TOKEN) + } + return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( - STEP_USER_DATA_SCHEMA, user_input or reconfigure_entry.data + STEP_USER_DATA_SCHEMA, suggested_values ), errors=errors, ) + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle reauthorization request from Home Assistant.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle reauthorization confirmation.""" + errors: dict[str, str] = {} + reauth_entry = self._get_reauth_entry() + + if user_input is not None: + user_input[CONF_URL] = reauth_entry.data[CONF_URL] + try: + await validate_input(self.hass, user_input) + except CannotConnect: + errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" + except Exception: + _LOGGER.exception("Unexpected exception during Gatus reauth") + errors["base"] = "unknown" + else: + return self.async_update_reload_and_abort( + reauth_entry, + data_updates=user_input, + ) + + schema = vol.Schema( + { + vol.Optional(CONF_USERNAME): TextSelector( + TextSelectorConfig( + type=TextSelectorType.TEXT, + autocomplete="username", + ), + ), + vol.Optional(CONF_PASSWORD): TextSelector( + TextSelectorConfig( + type=TextSelectorType.PASSWORD, + autocomplete="current-password", + ), + ), + vol.Optional(CONF_TOKEN): TextSelector( + TextSelectorConfig( + type=TextSelectorType.PASSWORD, + ), + ), + } + ) + + suggested_values = { + key: val + for key, val in (user_input or reauth_entry.data).items() + if key not in (CONF_PASSWORD, CONF_TOKEN) + } + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=self.add_suggested_values_to_schema(schema, suggested_values), + errors=errors, + ) + class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect to the server.""" + + +class InvalidAuth(HomeAssistantError): + """Error to indicate there is invalid auth.""" diff --git a/homeassistant/components/gatus/coordinator.py b/homeassistant/components/gatus/coordinator.py index 9200ed6d40b4..aad35f475c8e 100644 --- a/homeassistant/components/gatus/coordinator.py +++ b/homeassistant/components/gatus/coordinator.py @@ -4,10 +4,12 @@ from datetime import timedelta import logging from typing import override -from gatus_api import EndpointStatus, GatusClient, GatusClientError +from gatus_api import EndpointStatus, GatusAuthError, GatusClient, GatusClientError from homeassistant.config_entries import ConfigEntry +from homeassistant.const import CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers import device_registry as dr from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed @@ -26,7 +28,13 @@ class GatusDataUpdateCoordinator(DataUpdateCoordinator[dict[str, EndpointStatus] def __init__(self, hass: HomeAssistant, entry: GatusConfigEntry, url: str) -> None: """Initialize the coordinator.""" self.url = url.rstrip("/") - self.client = GatusClient(url=self.url, session=async_get_clientsession(hass)) + self.client = GatusClient( + url=self.url, + session=async_get_clientsession(hass), + username=entry.data.get(CONF_USERNAME), + password=entry.data.get(CONF_PASSWORD), + token=entry.data.get(CONF_TOKEN), + ) self._entry_id = entry.entry_id self.last_update_time = dt_util.utcnow().replace(second=0, microsecond=0) device_registry = dr.async_get(hass) @@ -54,6 +62,8 @@ class GatusDataUpdateCoordinator(DataUpdateCoordinator[dict[str, EndpointStatus] self.last_update_time = dt_util.utcnow().replace(second=0, microsecond=0) try: raw_endpoints = await self.client.get_endpoints_statuses() + except GatusAuthError as err: + raise ConfigEntryAuthFailed from err except GatusClientError as err: raise UpdateFailed( translation_domain=DOMAIN, diff --git a/homeassistant/components/gatus/quality_scale.yaml b/homeassistant/components/gatus/quality_scale.yaml index 560e712ed6c6..462f466a5469 100644 --- a/homeassistant/components/gatus/quality_scale.yaml +++ b/homeassistant/components/gatus/quality_scale.yaml @@ -42,9 +42,7 @@ rules: integration-owner: done log-when-unavailable: done parallel-updates: done - reauthentication-flow: - status: exempt - comment: Integration does not use authentication. + reauthentication-flow: done test-coverage: done # Gold diff --git a/homeassistant/components/gatus/strings.json b/homeassistant/components/gatus/strings.json index 5ca73b61ae1d..f9b79d99244e 100644 --- a/homeassistant/components/gatus/strings.json +++ b/homeassistant/components/gatus/strings.json @@ -2,28 +2,55 @@ "config": { "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_service%]", + "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]", "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", "unknown": "[%key:common::config_flow::error::unknown%]" }, "step": { - "reconfigure": { + "reauth_confirm": { "data": { - "url": "[%key:common::config_flow::data::url%]" + "password": "[%key:common::config_flow::data::password%]", + "token": "[%key:common::config_flow::data::api_key%]", + "username": "[%key:common::config_flow::data::username%]" }, "data_description": { - "url": "[%key:component::gatus::config::step::user::data_description::url%]" + "password": "[%key:component::gatus::config::step::user::data_description::password%]", + "token": "[%key:component::gatus::config::step::user::data_description::token%]", + "username": "[%key:component::gatus::config::step::user::data_description::username%]" + }, + "description": "Please re-enter your credentials for Gatus." + }, + "reconfigure": { + "data": { + "password": "[%key:common::config_flow::data::password%]", + "token": "[%key:common::config_flow::data::api_key%]", + "url": "[%key:common::config_flow::data::url%]", + "username": "[%key:common::config_flow::data::username%]" + }, + "data_description": { + "password": "[%key:component::gatus::config::step::user::data_description::password%]", + "token": "[%key:component::gatus::config::step::user::data_description::token%]", + "url": "[%key:component::gatus::config::step::user::data_description::url%]", + "username": "[%key:component::gatus::config::step::user::data_description::username%]" }, "description": "[%key:component::gatus::config::step::user::description%]" }, "user": { "data": { - "url": "[%key:common::config_flow::data::url%]" + "password": "[%key:common::config_flow::data::password%]", + "token": "[%key:common::config_flow::data::api_key%]", + "url": "[%key:common::config_flow::data::url%]", + "username": "[%key:common::config_flow::data::username%]" }, "data_description": { - "url": "The full base URL of your Gatus status page instance including protocol and port." + "password": "Optional password for HTTP Basic Authentication.", + "token": "Optional API token / Bearer token for authentication.", + "url": "The full base URL of your Gatus status page instance including protocol and port.", + "username": "Optional username for HTTP Basic Authentication." }, "description": "Enter the network details for your Gatus status page instance. Make sure to include the protocol (e.g., `http://` or `https://`) and the port number if you are not using a standard port." } diff --git a/tests/components/gatus/test_config_flow.py b/tests/components/gatus/test_config_flow.py index 45d9bf8c1241..f01e62f4fcd7 100644 --- a/tests/components/gatus/test_config_flow.py +++ b/tests/components/gatus/test_config_flow.py @@ -2,7 +2,7 @@ from unittest.mock import AsyncMock -from gatus_api import GatusClientError +from gatus_api import GatusAuthError, GatusClientError import pytest from homeassistant import config_entries @@ -65,6 +65,7 @@ async def test_form_success_with_path( ("side_effect", "error_key"), [ (GatusClientError("Cannot connect"), "cannot_connect"), + (GatusAuthError("401 Unauthorized"), "invalid_auth"), (Exception("Unexpected backend explosion"), "unknown"), ], ) @@ -148,6 +149,7 @@ async def test_flow_reconfigure( ("side_effect", "error_key"), [ (GatusClientError("Cannot connect"), "cannot_connect"), + (GatusAuthError("401 Unauthorized"), "invalid_auth"), (Exception("Unexpected backend explosion"), "unknown"), ], ) @@ -215,3 +217,142 @@ async def test_flow_reconfigure_already_configured( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("mock_gatus_client") +async def test_form_success_with_credentials( + hass: HomeAssistant, mock_setup_entry: AsyncMock +) -> None: + """Test setup with username, password, and token credentials.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_URL: "http://gatus.example.com:8080", + "username": "user", + "password": "pass", + "token": "secret_token", + }, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == { + CONF_URL: "http://gatus.example.com:8080", + "username": "user", + "password": "pass", + "token": "secret_token", + } + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.usefixtures("mock_gatus_client") +async def test_flow_reconfigure_credentials( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reconfigure flow updating stored credentials.""" + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reconfigure_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_URL: "http://gatus.example.com:8080", + "username": "new_user", + "password": "new_password", + "token": "new_token", + }, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert mock_config_entry.data == { + CONF_URL: "http://gatus.example.com:8080", + "username": "new_user", + "password": "new_password", + "token": "new_token", + } + + +@pytest.mark.usefixtures("mock_gatus_client") +async def test_flow_reauth( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauth flow.""" + mock_config_entry.add_to_hass(hass) + result = await mock_config_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"], + { + "username": "reauth_user", + "password": "reauth_password", + }, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_URL: "http://gatus.example.com:8080", + "username": "reauth_user", + "password": "reauth_password", + } + + +@pytest.mark.parametrize( + ("side_effect", "error_key"), + [ + (GatusClientError("Cannot connect"), "cannot_connect"), + (GatusAuthError("401 Unauthorized"), "invalid_auth"), + (Exception("Unexpected backend explosion"), "unknown"), + ], +) +async def test_flow_reauth_errors( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_gatus_client: AsyncMock, + side_effect: Exception, + error_key: str, +) -> None: + """Test reauth flow errors and recovery.""" + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + + mock_gatus_client.get_endpoints_statuses.side_effect = side_effect + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"username": "user", "password": "wrong_password"}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error_key} + + mock_gatus_client.get_endpoints_statuses.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"username": "user", "password": "correct_password"}, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_URL: "http://gatus.example.com:8080", + "username": "user", + "password": "correct_password", + } diff --git a/tests/components/gatus/test_init.py b/tests/components/gatus/test_init.py index a1bbfa6c9eb7..027d9e35aaf2 100644 --- a/tests/components/gatus/test_init.py +++ b/tests/components/gatus/test_init.py @@ -3,7 +3,7 @@ from unittest.mock import AsyncMock from freezegun.api import FrozenDateTimeFactory -from gatus_api import GatusClientError +from gatus_api import GatusAuthError, GatusClientError import pytest from homeassistant.components.gatus.coordinator import GatusDataUpdateCoordinator @@ -48,6 +48,21 @@ async def test_setup_failure_retry( assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY +async def test_setup_failure_auth( + hass: HomeAssistant, + mock_gatus_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test that an authentication failure places the entry in SETUP_ERROR state.""" + mock_gatus_client.get_endpoints_statuses.side_effect = GatusAuthError( + "401 Unauthorized" + ) + + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + + @pytest.mark.usefixtures("mock_gatus_client") async def test_remove_stale_device_runtime( hass: HomeAssistant,