Implement OAuth2 re-authentication flow for Google Health (#175893)

This commit is contained in:
Allen Porter
2026-07-08 09:14:12 +02:00
committed by GitHub
parent 050065ae70
commit 7aae637eeb
5 changed files with 162 additions and 6 deletions
@@ -1,5 +1,6 @@
"""Config flow for Google Health."""
from collections.abc import Mapping
import logging
from typing import Any, override
@@ -7,7 +8,7 @@ from google_health_api import GoogleHealthApi
from google_health_api.const import HealthApiScope
from google_health_api.exceptions import GoogleHealthApiError
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
@@ -40,6 +41,20 @@ class OAuth2FlowHandler(
"prompt": "consent",
}
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauth dialog."""
if user_input is None:
return self.async_show_form(step_id="reauth_confirm")
return await self.async_step_user()
@override
async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
scopes = data.get(CONF_TOKEN, {}).get("scope", "").split()
@@ -62,6 +77,9 @@ class OAuth2FlowHandler(
return self.async_abort(reason="cannot_connect")
await self.async_set_unique_id(identity.health_user_id)
if self.source == SOURCE_REAUTH:
reauth_entry = self._get_reauth_entry()
return self.async_update_reload_and_abort(reauth_entry, data=data)
self._abort_if_unique_id_configured()
display_name = None
@@ -44,7 +44,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done
# Gold
@@ -16,6 +16,7 @@
"oauth_implementation_unavailable": "[%key:common::config_flow::abort::oauth2_implementation_unavailable%]",
"oauth_timeout": "[%key:common::config_flow::abort::oauth2_timeout%]",
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"user_rejected_authorize": "[%key:common::config_flow::abort::oauth2_user_rejected_authorize%]"
},
"create_entry": {
@@ -24,6 +25,10 @@
"step": {
"pick_implementation": {
"title": "[%key:common::config_flow::title::oauth2_pick_implementation%]"
},
"reauth_confirm": {
"description": "The Google Health integration needs to re-authenticate your account",
"title": "[%key:common::config_flow::title::reauth%]"
}
}
},
@@ -1,11 +1,12 @@
"""Test the Google Health config flow."""
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, patch
from google_health_api.exceptions import GoogleHealthApiError
from google_health_api.model import Identity
import pytest
from homeassistant import config_entries
from homeassistant.components.google_health.const import (
DOMAIN,
OAUTH2_AUTHORIZE,
@@ -17,9 +18,14 @@ from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_entry_oauth2_flow
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
API_BASE_URL = "https://health.googleapis.com/v4/users/me"
IDENTITY_URL = f"{API_BASE_URL}/identity"
USERINFO_URL = "https://www.googleapis.com/oauth2/v3/userinfo"
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
@@ -254,3 +260,94 @@ async def test_config_flow_profile_name_error(
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Google Health"
@pytest.mark.usefixtures("current_request_with_host")
async def test_reauth_flow(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
setup_credentials: None,
) -> None:
"""Test reauth flow completes successfully."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": "google",
"token": {
"access_token": "old-access-token",
"refresh_token": "old-refresh-token",
"scope": " ".join(OAUTH_SCOPES),
},
},
unique_id="mock-health-user-id",
)
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"entry_id": config_entry.entry_id,
},
data=config_entry.data,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.EXTERNAL_STEP
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
client = await hass_client_no_auth()
await client.get(f"/auth/external/callback?code=abcd&state={state}")
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "new-refresh-token",
"access_token": "new-access-token",
"type": "Bearer",
"expires_in": 60,
"scope": " ".join(OAUTH_SCOPES),
},
)
aioclient_mock.get(
IDENTITY_URL,
json={
"name": "users/me/identity",
"healthUserId": "mock-health-user-id",
},
)
aioclient_mock.get(
USERINFO_URL,
json={
"givenName": "Allen",
"name": "Allen Porter",
},
)
with patch(
"homeassistant.components.google_health.async_setup_entry", return_value=True
) as mock_setup:
result2 = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reauth_successful"
assert config_entry.data["token"]["access_token"] == "new-access-token"
assert config_entry.data["token"]["refresh_token"] == "new-refresh-token"
assert len(mock_setup.mock_calls) == 1
+39 -3
View File
@@ -1,21 +1,25 @@
"""Tests for Google Health integration lifecycle (init/unloading)."""
from collections.abc import Awaitable, Callable
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from google_health_api.exceptions import (
GoogleHealthApiError,
HealthApiForbiddenException,
HealthAuthException,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.google_health.coordinator import POLLING_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry
from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.usefixtures("mock_google_health_client")
@@ -64,7 +68,8 @@ async def test_setup_auth_error(
assert config_entry.state is config_entries.ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 0
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.usefixtures("mock_google_health_client")
@@ -81,7 +86,8 @@ async def test_setup_missing_scopes(
assert config_entry.state is config_entries.ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 0
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.usefixtures("mock_google_health_client")
@@ -151,3 +157,33 @@ async def test_setup_oauth_implementation_unavailable(
await hass.async_block_till_done()
assert config_entry.state is config_entries.ConfigEntryState.SETUP_RETRY
@pytest.mark.usefixtures("mock_google_health_client")
async def test_runtime_auth_error(
hass: HomeAssistant,
config_entry: MockConfigEntry,
integration_setup: Callable[[], Awaitable[bool]],
mock_google_health_client: AsyncMock,
) -> None:
"""Test runtime auth failure triggers a reauth flow."""
# Setup the integration
assert await integration_setup()
assert config_entry.state is config_entries.ConfigEntryState.LOADED
# Mock an authorization error on subsequent update refresh
mock_google_health_client.steps.today.side_effect = HealthAuthException(
"Token expired"
)
# Trigger update by advancing time
async_fire_time_changed(
hass,
dt_util.utcnow() + POLLING_INTERVAL + timedelta(seconds=1),
)
await hass.async_block_till_done()
# Verify that the flow was initiated
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"