Skip to content

Commit

Permalink
Add reauth for missing token scope in Husqvarna Automower (#117098)
Browse files Browse the repository at this point in the history
* Add repair for wrong token scope to Husqvarna Automower

* avoid new installations with missing scope

* tweaks

* just reauth

* texts

* Add link to correct account

* Update homeassistant/components/husqvarna_automower/strings.json

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/husqvarna_automower/strings.json

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Update homeassistant/components/husqvarna_automower/strings.json

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Add comment

* directly assert mock_missing_scope_config_entry.state is loaded

* assert that a flow is started

* pass complete url to strings and simplify texts

* shorten long line

* address review

* simplify tests

* grammar

* remove obsolete fixture

* fix test

* Update tests/components/husqvarna_automower/test_init.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* test if reauth flow has started

---------

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
  • Loading branch information
Thomas55555 and MartinHjelmare committed May 13, 2024
1 parent 9c97269 commit b299684
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 14 deletions.
5 changes: 5 additions & 0 deletions homeassistant/components/husqvarna_automower/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator

if "amc:api" not in entry.data["token"]["scope"]:
# We raise ConfigEntryAuthFailed here because the websocket can't be used
# without the scope. So only polling would be possible.
raise ConfigEntryAuthFailed

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True

Expand Down
27 changes: 27 additions & 0 deletions homeassistant/components/husqvarna_automower/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
from .const import DOMAIN, NAME

_LOGGER = logging.getLogger(__name__)

CONF_USER_ID = "user_id"
HUSQVARNA_DEV_PORTAL_URL = "https://developer.husqvarnagroup.cloud/applications"


class HusqvarnaConfigFlowHandler(
Expand All @@ -29,8 +31,14 @@ class HusqvarnaConfigFlowHandler(
async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
"""Create an entry for the flow."""
token = data[CONF_TOKEN]
if "amc:api" not in token["scope"] and not self.reauth_entry:
return self.async_abort(reason="missing_amc_scope")
user_id = token[CONF_USER_ID]
if self.reauth_entry:
if "amc:api" not in token["scope"]:
return self.async_update_reload_and_abort(
self.reauth_entry, data=data, reason="missing_amc_scope"
)
if self.reauth_entry.unique_id != user_id:
return self.async_abort(reason="wrong_account")
return self.async_update_reload_and_abort(self.reauth_entry, data=data)
Expand All @@ -56,6 +64,9 @@ async def async_step_reauth(
self.reauth_entry = self.hass.config_entries.async_get_entry(
self.context["entry_id"]
)
if self.reauth_entry is not None:
if "amc:api" not in self.reauth_entry.data["token"]["scope"]:
return await self.async_step_missing_scope()
return await self.async_step_reauth_confirm()

async def async_step_reauth_confirm(
Expand All @@ -65,3 +76,19 @@ async def async_step_reauth_confirm(
if user_input is None:
return self.async_show_form(step_id="reauth_confirm")
return await self.async_step_user()

async def async_step_missing_scope(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauth for missing scope."""
if user_input is None and self.reauth_entry is not None:
token_structured = structure_token(
self.reauth_entry.data["token"]["access_token"]
)
return self.async_show_form(
step_id="missing_scope",
description_placeholders={
"application_url": f"{HUSQVARNA_DEV_PORTAL_URL}/{token_structured.client_id}"
},
)
return await self.async_step_user()
7 changes: 6 additions & 1 deletion homeassistant/components/husqvarna_automower/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
"title": "[%key:common::config_flow::title::reauth%]",
"description": "The Husqvarna Automower integration needs to re-authenticate your account"
},
"missing_scope": {
"title": "Your account is missing some API connections",
"description": "For the best experience with this integration both the `Authentication API` and the `Automower Connect API` should be connected. Please make sure that both of them are connected to your account in the [Husqvarna Developer Portal]({application_url})."
},
"pick_implementation": {
"title": "[%key:common::config_flow::title::oauth2_pick_implementation%]"
}
Expand All @@ -22,7 +26,8 @@
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
"oauth_failed": "[%key:common::config_flow::abort::oauth2_failed%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"wrong_account": "You can only reauthenticate this entry with the same Husqvarna account."
"wrong_account": "You can only reauthenticate this entry with the same Husqvarna account.",
"missing_amc_scope": "The `Authentication API` and the `Automower Connect API` are not connected to your application in the Husqvarna Developer Portal."
},
"create_entry": {
"default": "[%key:common::config_flow::create_entry::authenticated%]"
Expand Down
12 changes: 9 additions & 3 deletions tests/components/husqvarna_automower/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@


@pytest.fixture(name="jwt")
def load_jwt_fixture():
def load_jwt_fixture() -> str:
"""Load Fixture data."""
return load_fixture("jwt", DOMAIN)

Expand All @@ -33,8 +33,14 @@ def mock_expires_at() -> float:
return time.time() + 3600


@pytest.fixture(name="scope")
def mock_scope() -> str:
"""Fixture to set correct scope for the token."""
return "iam:read amc:api"


@pytest.fixture
def mock_config_entry(jwt, expires_at: int) -> MockConfigEntry:
def mock_config_entry(jwt: str, expires_at: int, scope: str) -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
version=1,
Expand All @@ -44,7 +50,7 @@ def mock_config_entry(jwt, expires_at: int) -> MockConfigEntry:
"auth_implementation": DOMAIN,
"token": {
"access_token": jwt,
"scope": "iam:read amc:api",
"scope": scope,
"expires_in": 86399,
"refresh_token": "3012bc9f-7a65-4240-b817-9154ffdcc30f",
"provider": "husqvarna",
Expand Down
51 changes: 41 additions & 10 deletions tests/components/husqvarna_automower/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from unittest.mock import AsyncMock, patch

import pytest

from homeassistant import config_entries
from homeassistant.components.husqvarna_automower.const import (
DOMAIN,
Expand All @@ -21,12 +23,21 @@
from tests.typing import ClientSessionGenerator


@pytest.mark.parametrize(
("new_scope", "amount"),
[
("iam:read amc:api", 1),
("iam:read", 0),
],
)
async def test_full_flow(
hass: HomeAssistant,
hass_client_no_auth,
aioclient_mock: AiohttpClientMocker,
current_request_with_host,
jwt,
jwt: str,
new_scope: str,
amount: int,
) -> None:
"""Check full flow."""
result = await hass.config_entries.flow.async_init(
Expand Down Expand Up @@ -56,7 +67,7 @@ async def test_full_flow(
OAUTH2_TOKEN,
json={
"access_token": jwt,
"scope": "iam:read amc:api",
"scope": new_scope,
"expires_in": 86399,
"refresh_token": "mock-refresh-token",
"provider": "husqvarna",
Expand All @@ -72,8 +83,8 @@ async def test_full_flow(
) as mock_setup:
await hass.config_entries.flow.async_configure(result["flow_id"])

assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup.mock_calls) == 1
assert len(hass.config_entries.async_entries(DOMAIN)) == amount
assert len(mock_setup.mock_calls) == amount


async def test_config_non_unique_profile(
Expand Down Expand Up @@ -129,14 +140,25 @@ async def test_config_non_unique_profile(
assert result["reason"] == "already_configured"


@pytest.mark.parametrize(
("scope", "step_id", "reason", "new_scope"),
[
("iam:read amc:api", "reauth_confirm", "reauth_successful", "iam:read amc:api"),
("iam:read", "missing_scope", "reauth_successful", "iam:read amc:api"),
("iam:read", "missing_scope", "missing_amc_scope", "iam:read"),
],
)
async def test_reauth(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
mock_config_entry: MockConfigEntry,
current_request_with_host: None,
mock_automower_client: AsyncMock,
jwt,
jwt: str,
step_id: str,
new_scope: str,
reason: str,
) -> None:
"""Test the reauthentication case updates the existing config entry."""

Expand All @@ -148,7 +170,7 @@ async def test_reauth(
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
result = flows[0]
assert result["step_id"] == "reauth_confirm"
assert result["step_id"] == step_id

result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
state = config_entry_oauth2_flow._encode_jwt(
Expand All @@ -172,7 +194,7 @@ async def test_reauth(
OAUTH2_TOKEN,
json={
"access_token": "mock-updated-token",
"scope": "iam:read amc:api",
"scope": new_scope,
"expires_in": 86399,
"refresh_token": "mock-refresh-token",
"provider": "husqvarna",
Expand All @@ -191,7 +213,7 @@ async def test_reauth(
assert len(hass.config_entries.async_entries(DOMAIN)) == 1

assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
assert result.get("reason") == reason

assert mock_config_entry.unique_id == USER_ID
assert "token" in mock_config_entry.data
Expand All @@ -200,6 +222,12 @@ async def test_reauth(
assert mock_config_entry.data["token"].get("refresh_token") == "mock-refresh-token"


@pytest.mark.parametrize(
("user_id", "reason"),
[
("wrong_user_id", "wrong_account"),
],
)
async def test_reauth_wrong_account(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
Expand All @@ -208,6 +236,9 @@ async def test_reauth_wrong_account(
current_request_with_host: None,
mock_automower_client: AsyncMock,
jwt,
user_id: str,
reason: str,
scope: str,
) -> None:
"""Test the reauthentication aborts, if user tries to reauthenticate with another account."""

Expand Down Expand Up @@ -247,7 +278,7 @@ async def test_reauth_wrong_account(
"expires_in": 86399,
"refresh_token": "mock-refresh-token",
"provider": "husqvarna",
"user_id": "wrong-user-id",
"user_id": user_id,
"token_type": "Bearer",
"expires_at": 1697753347,
},
Expand All @@ -262,7 +293,7 @@ async def test_reauth_wrong_account(
assert len(hass.config_entries.async_entries(DOMAIN)) == 1

assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "wrong_account"
assert result.get("reason") == reason

assert mock_config_entry.unique_id == USER_ID
assert "token" in mock_config_entry.data
Expand Down
20 changes: 20 additions & 0 deletions tests/components/husqvarna_automower/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,26 @@ async def test_load_unload_entry(
assert entry.state is ConfigEntryState.NOT_LOADED


@pytest.mark.parametrize(
("scope"),
[
("iam:read"),
],
)
async def test_load_missing_scope(
hass: HomeAssistant,
mock_automower_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test if the entry starts a reauth with the missing token scope."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
result = flows[0]
assert result["step_id"] == "missing_scope"


@pytest.mark.parametrize(
("expires_at", "status", "expected_state"),
[
Expand Down

0 comments on commit b299684

Please sign in to comment.