mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Add two-factor authentication to Renault (#186126)
This commit is contained in:
@@ -7,13 +7,24 @@ from typing import TYPE_CHECKING, Any, override
|
||||
import aiohttp
|
||||
import probatio
|
||||
from renault_api.const import AVAILABLE_LOCALES
|
||||
from renault_api.gigya.exceptions import GigyaException
|
||||
from renault_api.gigya.exceptions import (
|
||||
GigyaException,
|
||||
InvalidVerificationCodeException,
|
||||
PendingTwoFactorAuthenticationException,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import (
|
||||
SOURCE_REAUTH,
|
||||
SOURCE_RECONFIGURE,
|
||||
ConfigFlow,
|
||||
ConfigFlowResult,
|
||||
)
|
||||
from homeassistant.const import CONF_CODE, CONF_EMAIL
|
||||
from homeassistant.helpers.selector import (
|
||||
SelectOptionDict,
|
||||
SelectSelector,
|
||||
SelectSelectorConfig,
|
||||
)
|
||||
|
||||
from .const import DOMAIN, RenaultConfigurationKeys
|
||||
from .renault_hub import RenaultHub
|
||||
@@ -32,6 +43,7 @@ USER_SCHEMA = probatio.Schema(
|
||||
REAUTH_SCHEMA = probatio.Schema(
|
||||
{probatio.Required(RenaultConfigurationKeys.PASSWORD): str}
|
||||
)
|
||||
TWO_FACTOR_CODE_SCHEMA = probatio.Schema({probatio.Required(CONF_CODE): str})
|
||||
|
||||
|
||||
class RenaultFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
@@ -42,6 +54,8 @@ class RenaultFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
def __init__(self) -> None:
|
||||
"""Initialize the Renault config flow."""
|
||||
self.renault_config: dict[str, Any] = {}
|
||||
self._two_factor_emails: dict[str, str] = {}
|
||||
self._two_factor_email: str = ""
|
||||
|
||||
@override
|
||||
async def async_step_user(
|
||||
@@ -58,24 +72,27 @@ class RenaultFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
self.renault_config.update(user_input)
|
||||
self.renault_config.update(AVAILABLE_LOCALES[locale])
|
||||
self.renault_hub = RenaultHub(self.hass, locale)
|
||||
if self.source == SOURCE_RECONFIGURE:
|
||||
self.renault_hub.set_device_ids(
|
||||
self._get_reconfigure_entry().data.get(
|
||||
RenaultConfigurationKeys.DEVICE_IDS, {}
|
||||
)
|
||||
)
|
||||
try:
|
||||
login_success = await self.renault_hub.attempt_login(
|
||||
user_input[RenaultConfigurationKeys.USERNAME],
|
||||
user_input[RenaultConfigurationKeys.PASSWORD],
|
||||
)
|
||||
except aiohttp.ClientConnectionError, GigyaException:
|
||||
except PendingTwoFactorAuthenticationException:
|
||||
return await self.async_step_two_factor_email()
|
||||
except aiohttp.ClientError, GigyaException:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
if login_success:
|
||||
if TYPE_CHECKING:
|
||||
assert self.renault_hub.login_token
|
||||
self.renault_config[RenaultConfigurationKeys.LOGIN_TOKEN] = (
|
||||
self.renault_hub.login_token
|
||||
)
|
||||
return await self.async_step_kamereon()
|
||||
return await self._async_login_complete()
|
||||
errors["base"] = "invalid_credentials"
|
||||
suggested_values = user_input
|
||||
elif self.source == SOURCE_RECONFIGURE:
|
||||
@@ -145,26 +162,29 @@ class RenaultFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
errors: dict[str, str] = {}
|
||||
reauth_entry = self._get_reauth_entry()
|
||||
if user_input:
|
||||
# Check credentials
|
||||
self.renault_config.update(user_input)
|
||||
self.renault_hub = RenaultHub(
|
||||
self.hass, reauth_entry.data[RenaultConfigurationKeys.LOCALE]
|
||||
)
|
||||
if await self.renault_hub.attempt_login(
|
||||
reauth_entry.data[RenaultConfigurationKeys.USERNAME],
|
||||
user_input[RenaultConfigurationKeys.PASSWORD],
|
||||
):
|
||||
if TYPE_CHECKING:
|
||||
assert self.renault_hub.login_token
|
||||
return self.async_update_reload_and_abort(
|
||||
reauth_entry,
|
||||
data_updates={
|
||||
RenaultConfigurationKeys.PASSWORD: user_input[
|
||||
RenaultConfigurationKeys.PASSWORD
|
||||
],
|
||||
RenaultConfigurationKeys.LOGIN_TOKEN: self.renault_hub.login_token,
|
||||
},
|
||||
self.renault_hub.set_device_ids(
|
||||
reauth_entry.data.get(RenaultConfigurationKeys.DEVICE_IDS, {})
|
||||
)
|
||||
try:
|
||||
login_success = await self.renault_hub.attempt_login(
|
||||
reauth_entry.data[RenaultConfigurationKeys.USERNAME],
|
||||
user_input[RenaultConfigurationKeys.PASSWORD],
|
||||
)
|
||||
errors = {"base": "invalid_credentials"}
|
||||
except PendingTwoFactorAuthenticationException:
|
||||
return await self.async_step_two_factor_email()
|
||||
except aiohttp.ClientError, GigyaException:
|
||||
errors["base"] = "cannot_connect"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
if login_success:
|
||||
return await self._async_login_complete()
|
||||
errors["base"] = "invalid_credentials"
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
@@ -177,6 +197,104 @@ class RenaultFlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
},
|
||||
)
|
||||
|
||||
async def async_step_two_factor_email(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Select the email address to send the two-factor authentication code to."""
|
||||
if user_input:
|
||||
return await self._async_request_two_factor_auth_code(
|
||||
user_input[CONF_EMAIL]
|
||||
)
|
||||
|
||||
try:
|
||||
emails = await self.renault_hub.get_two_factor_auth_emails()
|
||||
except aiohttp.ClientError, GigyaException:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
return self.async_abort(reason="unknown")
|
||||
self._two_factor_emails = {
|
||||
email.id: email.obfuscated or email.id for email in emails if email.id
|
||||
}
|
||||
if not self._two_factor_emails:
|
||||
return self.async_abort(reason="two_factor_no_email")
|
||||
if len(self._two_factor_emails) == 1:
|
||||
return await self._async_request_two_factor_auth_code(
|
||||
next(iter(self._two_factor_emails))
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="two_factor_email",
|
||||
data_schema=probatio.Schema(
|
||||
{
|
||||
probatio.Required(CONF_EMAIL): SelectSelector(
|
||||
SelectSelectorConfig(
|
||||
options=[
|
||||
SelectOptionDict(value=email_id, label=email)
|
||||
for email_id, email in self._two_factor_emails.items()
|
||||
]
|
||||
)
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
async def _async_request_two_factor_auth_code(
|
||||
self, email_id: str
|
||||
) -> ConfigFlowResult:
|
||||
"""Email the two-factor authentication code."""
|
||||
try:
|
||||
await self.renault_hub.request_two_factor_auth_code(email_id)
|
||||
except aiohttp.ClientError, GigyaException:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
return self.async_abort(reason="unknown")
|
||||
self._two_factor_email = self._two_factor_emails[email_id]
|
||||
return await self.async_step_two_factor_code()
|
||||
|
||||
async def async_step_two_factor_code(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Complete the login with the two-factor authentication code."""
|
||||
errors: dict[str, str] = {}
|
||||
if user_input:
|
||||
try:
|
||||
await self.renault_hub.complete_two_factor_auth(user_input[CONF_CODE])
|
||||
except InvalidVerificationCodeException:
|
||||
errors["base"] = "invalid_code"
|
||||
# Other failures may discard the pending login, so the code can't be retried.
|
||||
except aiohttp.ClientError, GigyaException:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
return self.async_abort(reason="unknown")
|
||||
else:
|
||||
return await self._async_login_complete()
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="two_factor_code",
|
||||
data_schema=TWO_FACTOR_CODE_SCHEMA,
|
||||
errors=errors,
|
||||
description_placeholders={CONF_EMAIL: self._two_factor_email},
|
||||
)
|
||||
|
||||
async def _async_login_complete(self) -> ConfigFlowResult:
|
||||
"""Store the login token and device ids once logged in."""
|
||||
if TYPE_CHECKING:
|
||||
assert self.renault_hub.login_token
|
||||
self.renault_config[RenaultConfigurationKeys.LOGIN_TOKEN] = (
|
||||
self.renault_hub.login_token
|
||||
)
|
||||
self.renault_config[RenaultConfigurationKeys.DEVICE_IDS] = (
|
||||
self.renault_hub.device_ids
|
||||
)
|
||||
if self.source == SOURCE_REAUTH:
|
||||
return self.async_update_reload_and_abort(
|
||||
self._get_reauth_entry(), data_updates=self.renault_config
|
||||
)
|
||||
return await self.async_step_kamereon()
|
||||
|
||||
async def async_step_reconfigure(
|
||||
self, user_input: Mapping[str, Any]
|
||||
) -> ConfigFlowResult:
|
||||
|
||||
@@ -10,6 +10,7 @@ DOMAIN = "renault"
|
||||
class RenaultConfigurationKeys:
|
||||
"""Configuration keys."""
|
||||
|
||||
DEVICE_IDS: Final = "device_ids"
|
||||
KAMEREON_ACCOUNT_ID: Final = "kamereon_account_id"
|
||||
LOCALE: Final = "locale"
|
||||
LOGIN_TOKEN: Final = "login_token"
|
||||
|
||||
@@ -11,6 +11,7 @@ from .const import RenaultConfigurationKeys
|
||||
from .renault_vehicle import RenaultVehicleProxy
|
||||
|
||||
TO_REDACT = {
|
||||
RenaultConfigurationKeys.DEVICE_IDS,
|
||||
RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID,
|
||||
RenaultConfigurationKeys.LOGIN_TOKEN,
|
||||
RenaultConfigurationKeys.PASSWORD,
|
||||
|
||||
@@ -8,7 +8,11 @@ from time import time
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from renault_api.exceptions import NotAuthenticatedException
|
||||
from renault_api.gigya.exceptions import InvalidCredentialsException
|
||||
from renault_api.gigya.exceptions import (
|
||||
InvalidCredentialsException,
|
||||
PendingTwoFactorAuthenticationException,
|
||||
)
|
||||
from renault_api.gigya.models import GigyaTfaEmail
|
||||
from renault_api.kamereon.exceptions import KamereonResponseException
|
||||
from renault_api.kamereon.models import KamereonVehiclesLink
|
||||
from renault_api.renault_account import RenaultAccount
|
||||
@@ -74,6 +78,15 @@ class RenaultHub:
|
||||
"""Return the Gigya login token obtained from a successful login."""
|
||||
return self._client.session.login_token
|
||||
|
||||
@property
|
||||
def device_ids(self) -> dict[str, str]:
|
||||
"""Return the Gigya device ids remembered after two-factor authentication."""
|
||||
return self._client.session.device_ids
|
||||
|
||||
def set_device_ids(self, device_ids: dict[str, str]) -> None:
|
||||
"""Restore Gigya device ids, so a remembered device skips two-factor auth."""
|
||||
self._client.session.set_device_ids(device_ids)
|
||||
|
||||
def set_throttled(self) -> None:
|
||||
"""We got throttled, we need to adjust the rate limit."""
|
||||
if self._got_throttled_at_time is None:
|
||||
@@ -100,14 +113,35 @@ class RenaultHub:
|
||||
return True
|
||||
return False
|
||||
|
||||
async def get_two_factor_auth_emails(self) -> list[GigyaTfaEmail]:
|
||||
"""Get the email addresses registered for two-factor authentication."""
|
||||
return await self._client.session.get_two_factor_auth_emails()
|
||||
|
||||
async def request_two_factor_auth_code(self, email_id: str) -> None:
|
||||
"""Email a two-factor authentication code."""
|
||||
await self._client.session.request_two_factor_auth_code(email_id)
|
||||
|
||||
async def complete_two_factor_auth(self, code: str) -> None:
|
||||
"""Complete the pending login with the emailed code."""
|
||||
await self._client.session.complete_two_factor_auth(code)
|
||||
|
||||
async def async_login(self, config_entry: RenaultConfigEntry) -> None:
|
||||
"""Log in with the stored login token, or fall back to the password."""
|
||||
if login_token := config_entry.data.get(RenaultConfigurationKeys.LOGIN_TOKEN):
|
||||
self._client.session.set_login_token(login_token)
|
||||
elif await self.attempt_login(
|
||||
config_entry.data[RenaultConfigurationKeys.USERNAME],
|
||||
config_entry.data[RenaultConfigurationKeys.PASSWORD],
|
||||
):
|
||||
return
|
||||
self.set_device_ids(
|
||||
config_entry.data.get(RenaultConfigurationKeys.DEVICE_IDS, {})
|
||||
)
|
||||
try:
|
||||
login_success = await self.attempt_login(
|
||||
config_entry.data[RenaultConfigurationKeys.USERNAME],
|
||||
config_entry.data[RenaultConfigurationKeys.PASSWORD],
|
||||
)
|
||||
except PendingTwoFactorAuthenticationException as exc:
|
||||
# The code can only be entered in the reauth flow.
|
||||
raise NotAuthenticatedException from exc
|
||||
if login_success:
|
||||
# Persist the login token so the next setup can skip the password.
|
||||
self._hass.config_entries.async_update_entry(
|
||||
config_entry,
|
||||
|
||||
@@ -2,11 +2,15 @@
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"kamereon_no_account": "Unable to find Kamereon account",
|
||||
"unique_id_mismatch": "The selected Kamereon account ID does not match the previous account ID"
|
||||
"two_factor_no_email": "No email address is registered for two-factor authentication on your Renault account",
|
||||
"unique_id_mismatch": "The selected Kamereon account ID does not match the previous account ID",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_code": "Invalid verification code",
|
||||
"invalid_credentials": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
@@ -34,6 +38,26 @@
|
||||
"description": "Please update your password for {username}",
|
||||
"title": "[%key:common::config_flow::title::reauth%]"
|
||||
},
|
||||
"two_factor_code": {
|
||||
"data": {
|
||||
"code": "Verification code"
|
||||
},
|
||||
"data_description": {
|
||||
"code": "The verification code sent to {email}"
|
||||
},
|
||||
"description": "Your Renault account requires two-factor authentication. Enter the verification code that was sent to {email}.",
|
||||
"title": "Two-factor authentication"
|
||||
},
|
||||
"two_factor_email": {
|
||||
"data": {
|
||||
"email": "[%key:common::config_flow::data::email%]"
|
||||
},
|
||||
"data_description": {
|
||||
"email": "The email address to send the verification code to"
|
||||
},
|
||||
"description": "Your Renault account requires two-factor authentication. Select the email address to send the verification code to.",
|
||||
"title": "[%key:component::renault::config::step::two_factor_code::title%]"
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"locale": "Locale",
|
||||
|
||||
@@ -10,12 +10,14 @@ FORBIDDEN_EXCEPTION = ForbiddenException(
|
||||
"err.func.wired.forbidden", "The access is forbidden"
|
||||
)
|
||||
MOCK_LOGIN_TOKEN = "sample-login-token"
|
||||
MOCK_DEVICE_IDS = {"gmid": "sample-gmid", "ucid": "sample-ucid"}
|
||||
|
||||
# Mock config data to be used across multiple tests
|
||||
MOCK_CONFIG = {
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
RenaultConfigurationKeys.LOGIN_TOKEN: MOCK_LOGIN_TOKEN,
|
||||
RenaultConfigurationKeys.DEVICE_IDS: MOCK_DEVICE_IDS,
|
||||
RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID: MOCK_ACCOUNT_ID,
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
}
|
||||
|
||||
@@ -201,6 +201,7 @@
|
||||
dict({
|
||||
'entry': dict({
|
||||
'data': dict({
|
||||
'device_ids': '**REDACTED**',
|
||||
'kamereon_account_id': '**REDACTED**',
|
||||
'locale': 'fr_FR',
|
||||
'login_token': '**REDACTED**',
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
"""Test the Renault config flow."""
|
||||
|
||||
from unittest.mock import AsyncMock, PropertyMock, patch
|
||||
from collections.abc import AsyncGenerator, Generator
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, Mock, PropertyMock, patch
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from renault_api.gigya.exceptions import InvalidCredentialsException
|
||||
from renault_api.gigya.exceptions import (
|
||||
GigyaException,
|
||||
InvalidCredentialsException,
|
||||
InvalidVerificationCodeException,
|
||||
PendingTwoFactorAuthenticationException,
|
||||
)
|
||||
from renault_api.gigya.models import GigyaTfaEmail
|
||||
from renault_api.kamereon import schemas
|
||||
from renault_api.renault_account import RenaultAccount
|
||||
from renault_api.renault_session import RenaultSession
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.renault.const import DOMAIN, RenaultConfigurationKeys
|
||||
from homeassistant.const import CONF_CODE, CONF_EMAIL
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
|
||||
from .const import MOCK_LOGIN_TOKEN
|
||||
from .const import MOCK_ACCOUNT_ID, MOCK_CONFIG, MOCK_DEVICE_IDS, MOCK_LOGIN_TOKEN
|
||||
|
||||
from tests.common import MockConfigEntry, async_load_fixture, get_schema_suggested_value
|
||||
|
||||
@@ -518,3 +527,445 @@ async def test_reconfigure_mismatch(
|
||||
assert config_entry.data[RenaultConfigurationKeys.LOCALE] == "fr_FR"
|
||||
|
||||
assert len(mock_setup_entry.mock_calls) == 0
|
||||
|
||||
|
||||
def _mock_complete_two_factor_auth(session: RenaultSession, code: str) -> None:
|
||||
"""Log in and remember the device like a successful 2FA would."""
|
||||
session.set_login_token(MOCK_LOGIN_TOKEN)
|
||||
session.set_device_ids(MOCK_DEVICE_IDS)
|
||||
|
||||
|
||||
def _mock_pending_login(session: RenaultSession, login_id: str, password: str) -> None:
|
||||
"""Fail the login like an account requiring two-factor authentication."""
|
||||
raise PendingTwoFactorAuthenticationException(
|
||||
403101, "Pending Two-Factor Authentication", "reg-token"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_pending_login() -> Generator[AsyncMock]:
|
||||
"""Mock a login that requires two-factor authentication."""
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.login",
|
||||
autospec=True,
|
||||
side_effect=_mock_pending_login,
|
||||
) as mock_login:
|
||||
yield mock_login
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_two_factor_auth(
|
||||
mock_pending_login: AsyncMock, two_factor_emails: list[GigyaTfaEmail]
|
||||
) -> Generator[AsyncMock]:
|
||||
"""Mock the two-factor authentication calls."""
|
||||
with (
|
||||
patch(
|
||||
"renault_api.renault_session.RenaultSession.get_two_factor_auth_emails",
|
||||
return_value=two_factor_emails,
|
||||
),
|
||||
patch(
|
||||
"renault_api.renault_session.RenaultSession.request_two_factor_auth_code",
|
||||
) as mock_request_code,
|
||||
patch(
|
||||
"renault_api.renault_session.RenaultSession.complete_two_factor_auth",
|
||||
autospec=True,
|
||||
side_effect=_mock_complete_two_factor_auth,
|
||||
),
|
||||
):
|
||||
yield mock_request_code
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def two_factor_emails() -> list[GigyaTfaEmail]:
|
||||
"""Email addresses registered for two-factor authentication."""
|
||||
return [GigyaTfaEmail(raw_data={}, id="email_id_1", obfuscated="e***@test.com")]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def mock_get_api_accounts(hass: HomeAssistant) -> AsyncGenerator[None]:
|
||||
"""Mock a single Kamereon account with a vehicle."""
|
||||
renault_account = RenaultAccount(
|
||||
"account_id_1",
|
||||
websession=aiohttp_client.async_get_clientsession(hass),
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"renault_api.renault_client.RenaultClient.get_api_accounts",
|
||||
return_value=[renault_account],
|
||||
),
|
||||
patch(
|
||||
"renault_api.renault_account.RenaultAccount.get_vehicles",
|
||||
return_value=schemas.KamereonVehiclesResponseSchema.loads(
|
||||
await async_load_fixture(hass, "vehicle_zoe_40.json", DOMAIN)
|
||||
),
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_api_accounts")
|
||||
async def test_config_flow_two_factor_auth(
|
||||
hass: HomeAssistant, mock_two_factor_auth: AsyncMock
|
||||
) -> None:
|
||||
"""Test the config flow with two-factor authentication."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
},
|
||||
)
|
||||
|
||||
# A single email address is used without asking.
|
||||
mock_two_factor_auth.assert_awaited_once_with("email_id_1")
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_code"
|
||||
assert result["description_placeholders"] == {CONF_EMAIL: "e***@test.com"}
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["title"] == "account_id_1"
|
||||
assert result["result"].unique_id == "account_id_1"
|
||||
assert result["data"][RenaultConfigurationKeys.PASSWORD] == "test"
|
||||
assert result["data"][RenaultConfigurationKeys.LOGIN_TOKEN] == MOCK_LOGIN_TOKEN
|
||||
assert result["data"][RenaultConfigurationKeys.DEVICE_IDS] == MOCK_DEVICE_IDS
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_api_accounts")
|
||||
@pytest.mark.parametrize(
|
||||
"two_factor_emails",
|
||||
[
|
||||
[
|
||||
GigyaTfaEmail(raw_data={}, id="email_id_1", obfuscated="e***@test.com"),
|
||||
GigyaTfaEmail(raw_data={}, id="email_id_2", obfuscated="o***@test.com"),
|
||||
]
|
||||
],
|
||||
)
|
||||
async def test_config_flow_two_factor_auth_multiple_emails(
|
||||
hass: HomeAssistant, mock_two_factor_auth: AsyncMock
|
||||
) -> None:
|
||||
"""Test the user selects the email address for two-factor authentication."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_email"
|
||||
mock_two_factor_auth.assert_not_awaited()
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_EMAIL: "email_id_2"}
|
||||
)
|
||||
|
||||
mock_two_factor_auth.assert_awaited_once_with("email_id_2")
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_code"
|
||||
assert result["description_placeholders"] == {CONF_EMAIL: "o***@test.com"}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["result"].unique_id == "account_id_1"
|
||||
assert result["data"][RenaultConfigurationKeys.DEVICE_IDS] == MOCK_DEVICE_IDS
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_api_accounts", "mock_two_factor_auth")
|
||||
async def test_config_flow_two_factor_invalid_code(hass: HomeAssistant) -> None:
|
||||
"""Test a wrong two-factor authentication code can be corrected."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.complete_two_factor_auth",
|
||||
side_effect=InvalidVerificationCodeException(400006, "Wrong verification code"),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "000000"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_code"
|
||||
assert result["errors"] == {"base": "invalid_code"}
|
||||
|
||||
# The pending login stays valid after a wrong code.
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["result"].unique_id == "account_id_1"
|
||||
assert result["data"][RenaultConfigurationKeys.LOGIN_TOKEN] == MOCK_LOGIN_TOKEN
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_api_accounts", "mock_two_factor_auth")
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "reason"),
|
||||
[
|
||||
(aiohttp.ClientConnectionError(), "cannot_connect"),
|
||||
(aiohttp.ClientResponseError(Mock(), (), status=500), "cannot_connect"),
|
||||
(GigyaException(), "cannot_connect"),
|
||||
(Exception(), "unknown"),
|
||||
],
|
||||
)
|
||||
async def test_config_flow_two_factor_code_abort(
|
||||
hass: HomeAssistant, exception: Exception, reason: str
|
||||
) -> None:
|
||||
"""Test the flow aborts on errors other than a wrong code."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.complete_two_factor_auth",
|
||||
side_effect=exception,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("target", "kwargs", "reason"),
|
||||
[
|
||||
pytest.param(
|
||||
"get_two_factor_auth_emails",
|
||||
{"side_effect": aiohttp.ClientConnectionError()},
|
||||
"cannot_connect",
|
||||
id="get_emails_connection_error",
|
||||
),
|
||||
pytest.param(
|
||||
"get_two_factor_auth_emails",
|
||||
{"return_value": []},
|
||||
"two_factor_no_email",
|
||||
id="no_email",
|
||||
),
|
||||
pytest.param(
|
||||
"request_two_factor_auth_code",
|
||||
{"side_effect": GigyaException()},
|
||||
"cannot_connect",
|
||||
id="request_code_error",
|
||||
),
|
||||
pytest.param(
|
||||
"request_two_factor_auth_code",
|
||||
{"side_effect": aiohttp.ClientResponseError(Mock(), (), status=500)},
|
||||
"cannot_connect",
|
||||
id="request_code_http_error",
|
||||
),
|
||||
pytest.param(
|
||||
"get_two_factor_auth_emails",
|
||||
{"side_effect": Exception()},
|
||||
"unknown",
|
||||
id="get_emails_unexpected_error",
|
||||
),
|
||||
pytest.param(
|
||||
"request_two_factor_auth_code",
|
||||
{"side_effect": Exception()},
|
||||
"unknown",
|
||||
id="request_code_unexpected_error",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_two_factor_auth")
|
||||
async def test_config_flow_two_factor_auth_abort(
|
||||
hass: HomeAssistant, target: str, kwargs: dict[str, Any], reason: str
|
||||
) -> None:
|
||||
"""Test the flow aborts when the two-factor authentication code can't be sent."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
with patch(f"renault_api.renault_session.RenaultSession.{target}", **kwargs):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test",
|
||||
},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
(aiohttp.ClientConnectionError(), "cannot_connect"),
|
||||
(GigyaException(), "cannot_connect"),
|
||||
(Exception(), "unknown"),
|
||||
],
|
||||
)
|
||||
async def test_reauth_error(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
exception: Exception,
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test errors during reauth."""
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.login", side_effect=exception
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={RenaultConfigurationKeys.PASSWORD: "any"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {"base": error}
|
||||
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.login",
|
||||
autospec=True,
|
||||
side_effect=_mock_login,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={RenaultConfigurationKeys.PASSWORD: "any"},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_two_factor_auth")
|
||||
async def test_reauth_two_factor_auth(
|
||||
hass: HomeAssistant, mock_pending_login: AsyncMock
|
||||
) -> None:
|
||||
"""Test reauth with two-factor authentication restores the device ids first."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
**MOCK_CONFIG,
|
||||
RenaultConfigurationKeys.DEVICE_IDS: {
|
||||
"gmid": "old-gmid",
|
||||
"ucid": "old-ucid",
|
||||
},
|
||||
},
|
||||
unique_id=MOCK_ACCOUNT_ID,
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
|
||||
device_ids: list[dict[str, str]] = []
|
||||
|
||||
def _record_device_ids(
|
||||
session: RenaultSession, login_id: str, password: str
|
||||
) -> None:
|
||||
device_ids.append(session.device_ids)
|
||||
_mock_pending_login(session, login_id, password)
|
||||
|
||||
mock_pending_login.side_effect = _record_device_ids
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={RenaultConfigurationKeys.PASSWORD: "new-password"},
|
||||
)
|
||||
|
||||
assert device_ids == [{"gmid": "old-gmid", "ucid": "old-ucid"}]
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_code"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert config_entry.data[RenaultConfigurationKeys.PASSWORD] == "new-password"
|
||||
assert config_entry.data[RenaultConfigurationKeys.LOGIN_TOKEN] == MOCK_LOGIN_TOKEN
|
||||
assert config_entry.data[RenaultConfigurationKeys.DEVICE_IDS] == MOCK_DEVICE_IDS
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_api_accounts", "mock_two_factor_auth")
|
||||
async def test_reconfigure_two_factor_auth(
|
||||
hass: HomeAssistant,
|
||||
mock_setup_entry: AsyncMock,
|
||||
config_entry: MockConfigEntry,
|
||||
mock_pending_login: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reconfigure with two-factor authentication restores the device ids first."""
|
||||
hass.config_entries.async_update_entry(
|
||||
config_entry,
|
||||
data={
|
||||
**config_entry.data,
|
||||
RenaultConfigurationKeys.DEVICE_IDS: {
|
||||
"gmid": "old-gmid",
|
||||
"ucid": "old-ucid",
|
||||
},
|
||||
},
|
||||
)
|
||||
result = await config_entry.start_reconfigure_flow(hass)
|
||||
|
||||
device_ids: list[dict[str, str]] = []
|
||||
|
||||
def _record_device_ids(
|
||||
session: RenaultSession, login_id: str, password: str
|
||||
) -> None:
|
||||
device_ids.append(session.device_ids)
|
||||
_mock_pending_login(session, login_id, password)
|
||||
|
||||
mock_pending_login.side_effect = _record_device_ids
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={
|
||||
RenaultConfigurationKeys.LOCALE: "fr_FR",
|
||||
RenaultConfigurationKeys.USERNAME: "email2@test.com",
|
||||
RenaultConfigurationKeys.PASSWORD: "test2",
|
||||
},
|
||||
)
|
||||
|
||||
assert device_ids == [{"gmid": "old-gmid", "ucid": "old-ucid"}]
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "two_factor_code"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_CODE: "123456"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
assert config_entry.data[RenaultConfigurationKeys.USERNAME] == "email2@test.com"
|
||||
assert config_entry.data[RenaultConfigurationKeys.PASSWORD] == "test2"
|
||||
assert config_entry.data[RenaultConfigurationKeys.LOGIN_TOKEN] == MOCK_LOGIN_TOKEN
|
||||
assert config_entry.data[RenaultConfigurationKeys.DEVICE_IDS] == MOCK_DEVICE_IDS
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
@@ -6,7 +6,11 @@ from unittest.mock import AsyncMock, Mock, patch
|
||||
import aiohttp
|
||||
import pytest
|
||||
from renault_api.exceptions import NotAuthenticatedException
|
||||
from renault_api.gigya.exceptions import GigyaException, InvalidCredentialsException
|
||||
from renault_api.gigya.exceptions import (
|
||||
GigyaException,
|
||||
InvalidCredentialsException,
|
||||
PendingTwoFactorAuthenticationException,
|
||||
)
|
||||
from renault_api.renault_session import RenaultSession
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
@@ -24,6 +28,7 @@ from homeassistant.setup import async_setup_component
|
||||
from .const import (
|
||||
FORBIDDEN_EXCEPTION,
|
||||
MOCK_ACCOUNT_ID,
|
||||
MOCK_DEVICE_IDS,
|
||||
MOCK_LOGIN_TOKEN,
|
||||
OTHER_ACCOUNT_ID,
|
||||
)
|
||||
@@ -107,13 +112,61 @@ async def test_setup_entry_password_login(
|
||||
)
|
||||
|
||||
|
||||
async def test_setup_entry_bad_password(
|
||||
@pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles")
|
||||
@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True)
|
||||
async def test_setup_entry_password_login_device_ids(
|
||||
hass: HomeAssistant, legacy_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test reauth is triggered when the stored password is invalid."""
|
||||
"""Test the remembered device ids are restored before a password login."""
|
||||
hass.config_entries.async_update_entry(
|
||||
legacy_config_entry,
|
||||
data={
|
||||
**legacy_config_entry.data,
|
||||
RenaultConfigurationKeys.DEVICE_IDS: MOCK_DEVICE_IDS,
|
||||
},
|
||||
)
|
||||
device_ids: list[dict[str, str]] = []
|
||||
|
||||
def _record_device_ids(
|
||||
session: RenaultSession, login_id: str, password: str
|
||||
) -> None:
|
||||
device_ids.append(session.device_ids)
|
||||
_mock_login(session, login_id, password)
|
||||
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.login",
|
||||
side_effect=InvalidCredentialsException(403042, "invalid loginID or password"),
|
||||
autospec=True,
|
||||
side_effect=_record_device_ids,
|
||||
):
|
||||
await hass.config_entries.async_setup(legacy_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert device_ids == [MOCK_DEVICE_IDS]
|
||||
assert legacy_config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"side_effect",
|
||||
[
|
||||
pytest.param(
|
||||
InvalidCredentialsException(403042, "invalid loginID or password"),
|
||||
id="invalid_credentials",
|
||||
),
|
||||
pytest.param(
|
||||
PendingTwoFactorAuthenticationException(
|
||||
403101, "Pending Two-Factor Authentication", "reg-token"
|
||||
),
|
||||
id="two_factor_auth",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_setup_entry_bad_password(
|
||||
hass: HomeAssistant, legacy_config_entry: MockConfigEntry, side_effect: Exception
|
||||
) -> None:
|
||||
"""Test reauth is triggered when the password login fails."""
|
||||
with patch(
|
||||
"renault_api.renault_session.RenaultSession.login",
|
||||
side_effect=side_effect,
|
||||
):
|
||||
await hass.config_entries.async_setup(legacy_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
Reference in New Issue
Block a user