| 1 |
"""Package to communicate with the authentication API.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from functools import lru_cache, partial |
| 7 |
import logging |
| 8 |
import random |
| 9 |
from typing import TYPE_CHECKING, Any |
| 10 |
|
| 11 |
import boto3 |
| 12 |
import botocore |
| 13 |
from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError |
| 14 |
import pycognito |
| 15 |
from pycognito.exceptions import ForceChangePasswordException, MFAChallengeException |
| 16 |
|
| 17 |
from ..const import MESSAGE_AUTH_FAIL |
| 18 |
from ..exceptions import CloudError |
| 19 |
from ..utils import expiration_from_token, seconds_as_dhms, utcnow |
| 20 |
|
| 21 |
if TYPE_CHECKING: |
| 22 |
from .. import Cloud, _ClientT |
| 23 |
|
| 24 |
_LOGGER = logging.getLogger(__name__) |
| 25 |
|
| 26 |
|
| 27 |
class Unauthenticated(CloudError): |
| 28 |
"""Raised when authentication failed.""" |
| 29 |
|
| 30 |
|
| 31 |
class MFARequired(CloudError): |
| 32 |
"""Raised when MFA is required.""" |
| 33 |
|
| 34 |
_mfa_tokens: dict[str, Any] |
| 35 |
|
| 36 |
def __init__(self, mfa_tokens: dict[str, Any]) -> None: |
| 37 |
"""Initialize MFA required error.""" |
| 38 |
super().__init__("MFA required.") |
| 39 |
self._mfa_tokens = mfa_tokens |
| 40 |
|
| 41 |
@property |
| 42 |
def mfa_tokens(self) -> dict[str, Any]: |
| 43 |
"""Return MFA tokens.""" |
| 44 |
return self._mfa_tokens |
| 45 |
|
| 46 |
|
| 47 |
class InvalidTotpCode(CloudError): |
| 48 |
"""Raised when the TOTP code is invalid.""" |
| 49 |
|
| 50 |
|
| 51 |
class UserNotFound(CloudError): |
| 52 |
"""Raised when a user is not found.""" |
| 53 |
|
| 54 |
|
| 55 |
class UserExists(CloudError): |
| 56 |
"""Raised when a username already exists.""" |
| 57 |
|
| 58 |
|
| 59 |
class UserNotConfirmed(CloudError): |
| 60 |
"""Raised when a user has not confirmed email yet.""" |
| 61 |
|
| 62 |
|
| 63 |
class CloudConnectionError(CloudError): |
| 64 |
"""Raised when unable to connect to the cloud.""" |
| 65 |
|
| 66 |
|
| 67 |
class PasswordChangeRequired(CloudError): |
| 68 |
"""Raised when a password change is required.""" |
| 69 |
|
| 70 |
# https://github.com/PyCQA/pylint/issues/1085 |
| 71 |
# pylint: disable=useless-super-delegation |
| 72 |
def __init__(self, message: str = "Password change required.") -> None: |
| 73 |
"""Initialize a password change required error.""" |
| 74 |
super().__init__(message) |
| 75 |
|
| 76 |
|
| 77 |
class UnknownError(CloudError): |
| 78 |
"""Raised when an unknown error occurs.""" |
| 79 |
|
| 80 |
|
| 81 |
AWS_EXCEPTIONS: dict[str, type[CloudError]] = { |
| 82 |
"CodeMismatchException": InvalidTotpCode, |
| 83 |
"UserNotFoundException": UserNotFound, |
| 84 |
"UserNotConfirmedException": UserNotConfirmed, |
| 85 |
"UsernameExistsException": UserExists, |
| 86 |
"NotAuthorizedException": Unauthenticated, |
| 87 |
"PasswordResetRequiredException": PasswordChangeRequired, |
| 88 |
"EndpointConnectionError": CloudConnectionError, |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
class CognitoAuth: |
| 93 |
"""Handle cloud auth.""" |
| 94 |
|
| 95 |
def __init__(self, cloud: Cloud[_ClientT]) -> None: |
| 96 |
"""Configure the auth api.""" |
| 97 |
self.cloud = cloud |
| 98 |
self._refresh_task: asyncio.Task | None = None |
| 99 |
self._session: boto3.Session | None = None |
| 100 |
self._request_lock = asyncio.Lock() |
| 101 |
|
| 102 |
cloud.iot.register_on_connect(self.on_connect) |
| 103 |
cloud.iot.register_on_disconnect(self.on_disconnect) |
| 104 |
|
| 105 |
async def _async_handle_token_refresh(self) -> None: |
| 106 |
"""Handle Cloud access token refresh.""" |
| 107 |
|
| 108 |
def _sleep_time() -> int: |
| 109 |
"""Generate token refresh sleep time.""" |
| 110 |
if expiration_time := expiration_from_token(self.cloud.access_token): |
| 111 |
seconds_left = expiration_time - int(utcnow().timestamp()) |
| 112 |
if (suggestion := seconds_left - random.randint(10, 610)) > 1: |
| 113 |
return suggestion |
| 114 |
|
| 115 |
# If we don't have a valid token, or it is about to expire, |
| 116 |
# refresh it in a random time between 40 minutes and 1 hour. |
| 117 |
return random.randint(2400, 3600) |
| 118 |
|
| 119 |
while True: |
| 120 |
try: |
| 121 |
sleep_time = _sleep_time() |
| 122 |
_LOGGER.debug( |
| 123 |
"Sleeping for %s before refreshing token", |
| 124 |
seconds_as_dhms(sleep_time), |
| 125 |
) |
| 126 |
await asyncio.sleep(sleep_time) |
| 127 |
await self.async_renew_access_token() |
| 128 |
except CloudError as err: |
| 129 |
_LOGGER.error("Can't refresh cloud token: %s", err) |
| 130 |
except asyncio.CancelledError: |
| 131 |
# Task is canceled, stop it. |
| 132 |
break |
| 133 |
|
| 134 |
async def on_connect(self) -> None: |
| 135 |
"""When the instance is connected.""" |
| 136 |
self._refresh_task = asyncio.create_task(self._async_handle_token_refresh()) |
| 137 |
|
| 138 |
async def on_disconnect(self) -> None: |
| 139 |
"""When the instance is disconnected.""" |
| 140 |
if self._refresh_task is not None: |
| 141 |
self._refresh_task.cancel() |
| 142 |
|
| 143 |
async def async_register( |
| 144 |
self, |
| 145 |
email: str, |
| 146 |
password: str, |
| 147 |
*, |
| 148 |
client_metadata: Any | None = None, |
| 149 |
) -> None: |
| 150 |
"""Register a new account.""" |
| 151 |
try: |
| 152 |
async with self._request_lock: |
| 153 |
cognito = await self.cloud.run_executor( |
| 154 |
self._create_cognito_client, |
| 155 |
) |
| 156 |
await self.cloud.run_executor( |
| 157 |
partial( |
| 158 |
cognito.register, |
| 159 |
email.lower(), |
| 160 |
password, |
| 161 |
client_metadata=client_metadata, |
| 162 |
), |
| 163 |
) |
| 164 |
|
| 165 |
except (ClientError, EndpointConnectionError) as err: |
| 166 |
raise _map_aws_exception(err) from err |
| 167 |
except BotoCoreError as err: |
| 168 |
raise UnknownError from err |
| 169 |
|
| 170 |
async def async_resend_email_confirm(self, email: str) -> None: |
| 171 |
"""Resend email confirmation.""" |
| 172 |
try: |
| 173 |
async with self._request_lock: |
| 174 |
cognito = await self.cloud.run_executor( |
| 175 |
partial(self._create_cognito_client, username=email), |
| 176 |
) |
| 177 |
await self.cloud.run_executor( |
| 178 |
partial( |
| 179 |
cognito.client.resend_confirmation_code, |
| 180 |
Username=email, |
| 181 |
ClientId=cognito.client_id, |
| 182 |
), |
| 183 |
) |
| 184 |
except (ClientError, EndpointConnectionError) as err: |
| 185 |
raise _map_aws_exception(err) from err |
| 186 |
except BotoCoreError as err: |
| 187 |
raise UnknownError from err |
| 188 |
|
| 189 |
async def async_forgot_password(self, email: str) -> None: |
| 190 |
"""Initialize forgotten password flow.""" |
| 191 |
try: |
| 192 |
async with self._request_lock: |
| 193 |
cognito = await self.cloud.run_executor( |
| 194 |
partial(self._create_cognito_client, username=email), |
| 195 |
) |
| 196 |
await self.cloud.run_executor(cognito.initiate_forgot_password) |
| 197 |
|
| 198 |
except (ClientError, EndpointConnectionError) as err: |
| 199 |
raise _map_aws_exception(err) from err |
| 200 |
except BotoCoreError as err: |
| 201 |
raise UnknownError from err |
| 202 |
|
| 203 |
async def async_login( |
| 204 |
self, |
| 205 |
email: str, |
| 206 |
password: str, |
| 207 |
*, |
| 208 |
check_connection: bool = False, |
| 209 |
) -> None: |
| 210 |
"""Log user in and fetch certificate.""" |
| 211 |
try: |
| 212 |
async with self._request_lock: |
| 213 |
assert not self.cloud.is_logged_in, "Cannot login if already logged in." |
| 214 |
|
| 215 |
cognito: pycognito.Cognito = await self.cloud.run_executor( |
| 216 |
partial(self._create_cognito_client, username=email), |
| 217 |
) |
| 218 |
|
| 219 |
async with asyncio.timeout(30): |
| 220 |
await self.cloud.run_executor( |
| 221 |
partial(cognito.authenticate, password=password), |
| 222 |
) |
| 223 |
|
| 224 |
if check_connection: |
| 225 |
await self.cloud.ensure_not_connected( |
| 226 |
access_token=cognito.access_token |
| 227 |
) |
| 228 |
|
| 229 |
task = await self.cloud.update_token( |
| 230 |
cognito.id_token, |
| 231 |
cognito.access_token, |
| 232 |
cognito.refresh_token, |
| 233 |
) |
| 234 |
|
| 235 |
if task: |
| 236 |
await task |
| 237 |
|
| 238 |
except MFAChallengeException as err: |
| 239 |
raise MFARequired(err.get_tokens()) from err |
| 240 |
|
| 241 |
except ForceChangePasswordException as err: |
| 242 |
raise PasswordChangeRequired from err |
| 243 |
|
| 244 |
except (ClientError, EndpointConnectionError) as err: |
| 245 |
raise _map_aws_exception(err) from err |
| 246 |
|
| 247 |
except BotoCoreError as err: |
| 248 |
raise UnknownError from err |
| 249 |
|
| 250 |
async def async_login_verify_totp( |
| 251 |
self, |
| 252 |
email: str, |
| 253 |
code: str, |
| 254 |
mfa_tokens: dict[str, Any], |
| 255 |
*, |
| 256 |
check_connection: bool = False, |
| 257 |
) -> None: |
| 258 |
"""Log user in and fetch certificate if MFA is required.""" |
| 259 |
try: |
| 260 |
async with self._request_lock: |
| 261 |
assert not self.cloud.is_logged_in, ( |
| 262 |
"Cannot verify TOTP if already logged in." |
| 263 |
) |
| 264 |
|
| 265 |
cognito: pycognito.Cognito = await self.cloud.run_executor( |
| 266 |
partial(self._create_cognito_client, username=email), |
| 267 |
) |
| 268 |
|
| 269 |
async with asyncio.timeout(30): |
| 270 |
await self.cloud.run_executor( |
| 271 |
partial( |
| 272 |
cognito.respond_to_software_token_mfa_challenge, |
| 273 |
code=code, |
| 274 |
mfa_tokens=mfa_tokens, |
| 275 |
), |
| 276 |
) |
| 277 |
|
| 278 |
if check_connection: |
| 279 |
await self.cloud.ensure_not_connected( |
| 280 |
access_token=cognito.access_token |
| 281 |
) |
| 282 |
|
| 283 |
task = await self.cloud.update_token( |
| 284 |
cognito.id_token, |
| 285 |
cognito.access_token, |
| 286 |
cognito.refresh_token, |
| 287 |
) |
| 288 |
|
| 289 |
if task: |
| 290 |
await task |
| 291 |
|
| 292 |
except (ClientError, EndpointConnectionError) as err: |
| 293 |
raise _map_aws_exception(err) from err |
| 294 |
|
| 295 |
except BotoCoreError as err: |
| 296 |
raise UnknownError from err |
| 297 |
|
| 298 |
async def async_check_token(self) -> None: |
| 299 |
"""Check that the token is valid and renew if necessary.""" |
| 300 |
async with self._request_lock: |
| 301 |
cognito = await self._async_authenticated_cognito() |
| 302 |
if not cognito.check_token(renew=False): |
| 303 |
return |
| 304 |
|
| 305 |
try: |
| 306 |
await self._async_renew_access_token() |
| 307 |
except (Unauthenticated, UserNotFound) as err: |
| 308 |
_LOGGER.error("Unable to refresh token: %s", err) |
| 309 |
|
| 310 |
self.cloud.client.user_message( |
| 311 |
"cloud_subscription_expired", |
| 312 |
"Home Assistant Cloud", |
| 313 |
MESSAGE_AUTH_FAIL, |
| 314 |
) |
| 315 |
|
| 316 |
# Don't await it because it could cancel this task |
| 317 |
asyncio.create_task(self.cloud.logout()) |
| 318 |
raise |
| 319 |
|
| 320 |
async def async_renew_access_token(self) -> None: |
| 321 |
"""Renew access token.""" |
| 322 |
async with self._request_lock: |
| 323 |
await self._async_renew_access_token() |
| 324 |
|
| 325 |
async def _async_renew_access_token(self) -> None: |
| 326 |
"""Renew access token internals. |
| 327 |
|
| 328 |
Does not consume lock. |
| 329 |
""" |
| 330 |
cognito = await self._async_authenticated_cognito() |
| 331 |
|
| 332 |
try: |
| 333 |
await self.cloud.run_executor(cognito.renew_access_token) |
| 334 |
await self.cloud.update_token(cognito.id_token, cognito.access_token) |
| 335 |
|
| 336 |
except (ClientError, EndpointConnectionError) as err: |
| 337 |
raise _map_aws_exception(err) from err |
| 338 |
|
| 339 |
except BotoCoreError as err: |
| 340 |
raise UnknownError from err |
| 341 |
|
| 342 |
async def _async_authenticated_cognito(self) -> pycognito.Cognito: |
| 343 |
"""Return an authenticated cognito instance.""" |
| 344 |
if self.cloud.access_token is None or self.cloud.refresh_token is None: |
| 345 |
raise Unauthenticated("No authentication found") |
| 346 |
|
| 347 |
return await self.cloud.run_executor( |
| 348 |
partial( |
| 349 |
self._create_cognito_client, |
| 350 |
access_token=self.cloud.access_token, |
| 351 |
refresh_token=self.cloud.refresh_token, |
| 352 |
), |
| 353 |
) |
| 354 |
|
| 355 |
def _create_cognito_client(self, **kwargs: Any) -> pycognito.Cognito: |
| 356 |
"""Create a new cognito client. |
| 357 |
|
| 358 |
NOTE: This will do I/O |
| 359 |
""" |
| 360 |
if self._session is None: |
| 361 |
self._session = boto3.session.Session() |
| 362 |
|
| 363 |
return _cached_cognito( |
| 364 |
user_pool_id=self.cloud.user_pool_id, |
| 365 |
client_id=self.cloud.cognito_client_id, |
| 366 |
user_pool_region=self.cloud.region, |
| 367 |
botocore_config=botocore.config.Config(signature_version=botocore.UNSIGNED), |
| 368 |
session=self._session, |
| 369 |
**kwargs, |
| 370 |
) |
| 371 |
|
| 372 |
|
| 373 |
def _map_aws_exception(err: ClientError | BotoCoreError) -> CloudError: |
| 374 |
"""Map AWS exception to our exceptions.""" |
| 375 |
if isinstance(err, BotoCoreError): |
| 376 |
return AWS_EXCEPTIONS.get(err.__class__.__name__, UnknownError)( |
| 377 |
err.kwargs.get("error", str(err)) |
| 378 |
) |
| 379 |
return AWS_EXCEPTIONS.get(err.response["Error"]["Code"], UnknownError)( |
| 380 |
err.response["Error"]["Message"] |
| 381 |
) |
| 382 |
|
| 383 |
|
| 384 |
@lru_cache(maxsize=2) |
| 385 |
def _cached_cognito( |
| 386 |
user_pool_id: str, |
| 387 |
client_id: str, |
| 388 |
user_pool_region: str, |
| 389 |
botocore_config: Any, |
| 390 |
session: Any, |
| 391 |
**kwargs: Any, |
| 392 |
) -> pycognito.Cognito: |
| 393 |
"""Create a cached cognito client. |
| 394 |
|
| 395 |
NOTE: This will do I/O |
| 396 |
""" |
| 397 |
return pycognito.Cognito( |
| 398 |
user_pool_id=user_pool_id, |
| 399 |
client_id=client_id, |
| 400 |
user_pool_region=user_pool_region, |
| 401 |
botocore_config=botocore_config, |
| 402 |
session=session, |
| 403 |
**kwargs, |
| 404 |
) |