Add authentication support to Gatus integration (#178663)

This commit is contained in:
Hamish
2026-08-26 20:12:21 +02:00
committed by GitHub
parent af87bac7f7
commit bd38ea70fc
6 changed files with 314 additions and 16 deletions
+111 -4
View File
@@ -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."""
+12 -2
View File
@@ -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,
@@ -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
+32 -5
View File
@@ -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."
}
+142 -1
View File
@@ -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",
}
+16 -1
View File
@@ -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,