Debian Codegraph @

hass_nabucasa/__init__.py

raw
1 """Component to integrate the Home Assistant cloud."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from collections.abc import Awaitable, Callable, Mapping
7 from datetime import datetime, timedelta
8 import json
9 import logging
10 from pathlib import Path
11 import random
12 import shutil
13 from typing import Any, Generic, Literal, TypeVar
14
15 from aiohttp import ClientSession
16 from atomicwrites import atomic_write
17 import jwt
18
19 from .account_api import AccountApi, AccountApiError
20 from .accounts_api import AccountsApi, AccountsApiError
21 from .alexa_api import (
22 AlexaAccessTokenDetails,
23 AlexaApi,
24 AlexaApiError,
25 AlexaApiNeedsRelinkError,
26 AlexaApiNoTokenError,
27 )
28 from .api import (
29 CloudApiClientError,
30 CloudApiCodedError,
31 CloudApiError,
32 CloudApiInvalidResponseError,
33 CloudApiNonRetryableError,
34 CloudApiTimeoutError,
35 )
36 from .auth import (
37 CognitoAuth,
38 InvalidTotpCode,
39 MFARequired,
40 PasswordChangeRequired,
41 Unauthenticated,
42 UnknownError,
43 UserExists,
44 UserNotConfirmed,
45 UserNotFound,
46 )
47 from .client import CloudClient
48 from .cloudhooks import CloudhookDetails, Cloudhooks
49 from .const import (
50 ACCOUNT_URL,
51 CONFIG_DIR,
52 DEFAULT_SERVERS,
53 DEFAULT_VALUES,
54 MODE_DEV,
55 STATE_CONNECTED,
56 CertificateStatus,
57 SubscriptionReconnectionReason,
58 )
59 from .events import (
60 CloudEvent,
61 CloudEventBus,
62 CloudEventType,
63 CloudhookCreatedEvent,
64 CloudhookDeletedEvent,
65 )
66 from .exceptions import (
67 CloudError,
68 NabuCasaAuthenticationError,
69 NabuCasaBaseError,
70 NabuCasaConnectionError,
71 NabuCasaNotLoggedInError,
72 )
73 from .files import Files, FilesError, StorageType, StoredFile, calculate_b64md5
74 from .google_report_state import GoogleReportState, GoogleReportStateError
75 from .ice_servers import IceServers, IceServersApiError
76 from .instance_api import InstanceApi, InstanceApiError, InstanceConnectionDetails
77 from .iot import CloudIoT
78 from .llm import (
79 LLMHandler,
80 )
81 from .payments_api import (
82 MigratePaypalAgreementInfo,
83 PaymentsApi,
84 PaymentsApiError,
85 SubscriptionInfo,
86 )
87 from .remote import RemoteLatencyLocationResult, RemoteUI
88 from .service_discovery import (
89 ServiceDiscovery,
90 ServiceDiscoveryAction,
91 ServiceDiscoveryError,
92 ServiceDiscoveryInvalidResponseError,
93 ServiceDiscoveryMissingActionError,
94 ServiceDiscoveryMissingParameterError,
95 )
96 from .utils import (
97 UTC,
98 CheckLatencyError,
99 CheckLatencyHostResult,
100 async_check_latency,
101 gather_callbacks,
102 parse_date,
103 seconds_as_dhms,
104 utcnow,
105 )
106 from .voice import Voice
107 from .voice_api import VoiceApi, VoiceApiError
108
109 __all__ = [
110 "MODE_DEV",
111 "AccountApiError",
112 "AccountsApi",
113 "AccountsApiError",
114 "AlexaAccessTokenDetails",
115 "AlexaApiError",
116 "AlexaApiNeedsRelinkError",
117 "AlexaApiNoTokenError",
118 "AlreadyConnectedError",
119 "CertificateStatus",
120 "CheckLatencyError",
121 "CheckLatencyHostResult",
122 "Cloud",
123 "CloudApiClientError",
124 "CloudApiCodedError",
125 "CloudApiError",
126 "CloudApiInvalidResponseError",
127 "CloudApiNonRetryableError",
128 "CloudApiTimeoutError",
129 "CloudClient",
130 "CloudError",
131 "CloudEvent",
132 "CloudEventBus",
133 "CloudEventType",
134 "CloudhookCreatedEvent",
135 "CloudhookDeletedEvent",
136 "CloudhookDetails",
137 "FilesError",
138 "GoogleReportStateError",
139 "IceServersApiError",
140 "InstanceApiError",
141 "InstanceConnectionDetails",
142 "InvalidTotpCode",
143 "MFARequired",
144 "MigratePaypalAgreementInfo",
145 "NabuCasaAuthenticationError",
146 "NabuCasaBaseError",
147 "NabuCasaConnectionError",
148 "NabuCasaNotLoggedInError",
149 "PasswordChangeRequired",
150 "PaymentsApiError",
151 "RemoteLatencyLocationResult",
152 "ServiceDiscovery",
153 "ServiceDiscoveryAction",
154 "ServiceDiscoveryError",
155 "ServiceDiscoveryInvalidResponseError",
156 "ServiceDiscoveryMissingActionError",
157 "ServiceDiscoveryMissingParameterError",
158 "StorageType",
159 "StoredFile",
160 "SubscriptionInfo",
161 "SubscriptionReconnectionReason",
162 "Unauthenticated",
163 "UnknownError",
164 "UserExists",
165 "UserNotConfirmed",
166 "UserNotFound",
167 "VoiceApiError",
168 "async_check_latency",
169 "calculate_b64md5",
170 ]
171
172 _ClientT = TypeVar("_ClientT", bound=CloudClient)
173
174
175 _LOGGER = logging.getLogger(__name__)
176
177
178 class AlreadyConnectedError(CloudError):
179 """Raised when a connection is already established."""
180
181 def __init__(self, *, details: InstanceConnectionDetails) -> None:
182 """Initialize an already connected error."""
183 super().__init__("instance_already_connected")
184 self.details = details
185
186
187 class Cloud(Generic[_ClientT]):
188 """Store the configuration of the cloud connection."""
189
190 def __init__(
191 self,
192 client: _ClientT,
193 mode: Literal["development", "production"],
194 *,
195 api_server: str | None = None,
196 cognito_client_id: str | None = None,
197 region: str | None = None,
198 user_pool_id: str | None = None,
199 account_link_server: str | None = None,
200 acme_server: str | None = None,
201 relayer_server: str | None = None,
202 remotestate_server: str | None = None,
203 discovery_service_actions: dict[ServiceDiscoveryAction, str] | None = None,
204 privileged_ping: bool = True,
205 **kwargs: Any, # noqa: ARG002
206 ) -> None:
207 """Create an instance of Cloud."""
208 self.client = client
209 self.mode = mode
210 self.privileged_ping = privileged_ping
211
212 self._on_initialized: list[Callable[[], Awaitable[None]]] = []
213 self._on_start: list[Callable[[], Awaitable[None]]] = []
214 self._on_stop: list[Callable[[], Awaitable[None]]] = []
215
216 self._init_task: asyncio.Task | None = None
217 self._subscription_reconnection_task: asyncio.Task | None = None
218
219 self.access_token: str | None = None
220 self.id_token: str | None = None
221 self.refresh_token: str | None = None
222 self.started: bool | None = None
223 self._connection_retry_count = 0
224
225 # Set reference
226 self.client.cloud = self
227
228 _values = DEFAULT_VALUES[mode]
229 _servers = DEFAULT_SERVERS[mode]
230
231 self.cognito_client_id = _values.get("cognito_client_id", cognito_client_id)
232 self.region = _values.get("region", region)
233 self.user_pool_id = _values.get("user_pool_id", user_pool_id)
234
235 self.account_link_server = _servers.get("account_link", account_link_server)
236 self.acme_server = _servers.get("acme", acme_server)
237 self.api_server = _servers.get("api", api_server)
238 self.relayer_server = _servers.get("relayer", relayer_server)
239 self.remotestate_server = _servers.get("remotestate", remotestate_server)
240
241 # Setup event bus before other components
242 self.events = CloudEventBus()
243
244 # Needs to be setup before other components
245 self.iot = CloudIoT(self)
246
247 # Setup the rest of the components
248 self.account = AccountApi(self)
249 self.accounts = AccountsApi(self)
250 self.llm = LLMHandler(self)
251 self.alexa_api = AlexaApi(self)
252 self.auth = CognitoAuth(self)
253 self.cloudhooks = Cloudhooks(self)
254 self.files = Files(self)
255 self.google_report_state = GoogleReportState(self)
256 self.ice_servers = IceServers(self)
257 self.instance = InstanceApi(self)
258 self.payments = PaymentsApi(self)
259 self.remote = RemoteUI(self)
260 self.service_discovery = ServiceDiscovery(
261 self,
262 action_overrides=discovery_service_actions,
263 )
264 self.voice = Voice(self)
265 self.voice_api = VoiceApi(self)
266
267 @property
268 def is_logged_in(self) -> bool:
269 """Get if cloud is logged in."""
270 return self.id_token is not None
271
272 @property
273 def is_connected(self) -> bool:
274 """Return True if we are connected."""
275 return self.iot.state == STATE_CONNECTED
276
277 @property
278 def websession(self) -> ClientSession:
279 """Return websession for connections."""
280 return self.client.websession
281
282 @property
283 def subscription_expired(self) -> bool:
284 """Return a boolean if the subscription has expired."""
285 return utcnow() > self.expiration_date + timedelta(days=7)
286
287 @property
288 def valid_subscription(self) -> bool:
289 """Return True if the subscription is valid."""
290 return (
291 self._subscription_reconnection_task is None
292 and not self.subscription_expired
293 )
294
295 @property
296 def expiration_date(self) -> datetime:
297 """Return the subscription expiration as a UTC datetime object."""
298 if (parsed_date := parse_date(self.claims["custom:sub-exp"])) is None:
299 raise ValueError(
300 f"Invalid expiration date ({self.claims['custom:sub-exp']})",
301 )
302 return datetime.combine(parsed_date, datetime.min.time()).replace(tzinfo=UTC)
303
304 @property
305 def username(self) -> str:
306 """Return the subscription username."""
307 return self.claims["cognito:username"]
308
309 @property
310 def claims(self) -> Mapping[str, str]:
311 """Return the claims from the id token."""
312 return self._decode_claims(str(self.id_token))
313
314 @property
315 def user_info_path(self) -> Path:
316 """Get path to the stored auth."""
317 return self.path(f"{self.mode}_auth.json")
318
319 async def ensure_not_connected(
320 self,
321 *,
322 access_token: str,
323 ) -> None:
324 """Raise AlreadyConnectedError if already connected."""
325 try:
326 await self.service_discovery.async_start_service_discovery()
327 except ServiceDiscoveryError as err:
328 _LOGGER.info("Failed to initialize service discovery: %s", err)
329
330 try:
331 connection = await self.instance.connection(
332 skip_token_check=True,
333 access_token=access_token,
334 )
335 except CloudError:
336 return
337
338 if connection["connected"]:
339 raise AlreadyConnectedError(details=connection["details"])
340
341 async def update_token(
342 self,
343 id_token: str,
344 access_token: str,
345 refresh_token: str | None = None,
346 ) -> asyncio.Task | None:
347 """Update the id and access token."""
348 self.id_token = id_token
349 self.access_token = access_token
350 if refresh_token is not None:
351 self.refresh_token = refresh_token
352
353 await self.run_executor(self._write_user_info)
354
355 if self.started is None:
356 return None
357
358 if not self.started and not self.subscription_expired:
359 self.started = True
360 return asyncio.create_task(self._start())
361
362 if self.started and self.subscription_expired:
363 self.started = False
364 await self.stop()
365
366 if self.subscription_expired:
367 self.async_initialize_subscription_reconnection_handler(
368 SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED
369 )
370
371 return None
372
373 def register_on_initialized(
374 self,
375 on_initialized_cb: Callable[[], Awaitable[None]],
376 ) -> None:
377 """Register an async on_initialized callback.
378
379 on_initialized callbacks are called after all on_start callbacks.
380 """
381 self._on_initialized.append(on_initialized_cb)
382
383 def register_on_start(self, on_start_cb: Callable[[], Awaitable[None]]) -> None:
384 """Register an async on_start callback."""
385 self._on_start.append(on_start_cb)
386
387 def register_on_stop(self, on_stop_cb: Callable[[], Awaitable[None]]) -> None:
388 """Register an async on_stop callback."""
389 self._on_stop.append(on_stop_cb)
390
391 def path(self, *parts: Any) -> Path:
392 """Get config path inside cloud dir.
393
394 Async friendly.
395 """
396 return Path(self.client.base_path, CONFIG_DIR, *parts)
397
398 def run_executor(self, callback: Callable, *args: Any) -> asyncio.Future:
399 """Run function inside executore.
400
401 Return a awaitable object.
402 """
403 return self.client.loop.run_in_executor(None, callback, *args)
404
405 async def login(
406 self, email: str, password: str, *, check_connection: bool = False
407 ) -> None:
408 """Log a user in."""
409 await self.auth.async_login(email, password, check_connection=check_connection)
410 await self.events.publish(CloudEvent(type=CloudEventType.LOGIN))
411
412 async def login_verify_totp(
413 self,
414 email: str,
415 code: str,
416 mfa_tokens: dict[str, Any],
417 *,
418 check_connection: bool = False,
419 ) -> None:
420 """Verify TOTP code during login."""
421 await self.auth.async_login_verify_totp(
422 email, code, mfa_tokens, check_connection=check_connection
423 )
424 await self.events.publish(CloudEvent(type=CloudEventType.LOGIN))
425
426 async def logout(self) -> None:
427 """Close connection and remove all credentials."""
428 await self.events.publish(CloudEvent(type=CloudEventType.LOGOUT))
429 self.id_token = None
430 self.access_token = None
431 self.refresh_token = None
432
433 self.started = False
434 await self.stop()
435
436 # Cleanup auth data
437 if self.user_info_path.exists():
438 await self.run_executor(self.user_info_path.unlink)
439
440 await self.client.logout_cleanups()
441
442 async def remove_data(self) -> None:
443 """Remove all stored data."""
444 if self.started:
445 raise ValueError("Cloud not stopped")
446
447 try:
448 await self.remote.reset_acme()
449 finally:
450 await self.run_executor(self._remove_data)
451
452 def _remove_data(self) -> None:
453 """Remove all stored data."""
454 base_path = self.path()
455
456 # Recursively remove .cloud
457 if base_path.is_dir():
458 shutil.rmtree(base_path)
459
460 # Guard against .cloud not being a directory
461 if base_path.exists():
462 base_path.unlink()
463
464 def _write_user_info(self) -> None:
465 """Write user info to a file."""
466 base_path = self.path()
467 if not base_path.exists():
468 base_path.mkdir()
469
470 with atomic_write(self.user_info_path, overwrite=True) as fp:
471 fp.write(
472 json.dumps(
473 {
474 "id_token": self.id_token,
475 "access_token": self.access_token,
476 "refresh_token": self.refresh_token,
477 },
478 indent=4,
479 ),
480 )
481 self.user_info_path.chmod(0o600)
482
483 async def initialize(self) -> None:
484 """Initialize the cloud component (load auth and maybe start)."""
485
486 def load_config() -> None | dict[str, Any]:
487 """Load config."""
488 # Ensure config dir exists
489 base_path = self.path()
490 if not base_path.exists():
491 base_path.mkdir()
492
493 if not self.user_info_path.exists():
494 return None
495
496 try:
497 content: dict[str, Any] = json.loads(
498 self.user_info_path.read_text(encoding="utf-8"),
499 )
500 except (ValueError, OSError) as err:
501 path = self.user_info_path.relative_to(self.client.base_path)
502 self.client.loop.call_soon_threadsafe(
503 self.client.user_message,
504 "load_auth_data",
505 "Home Assistant Cloud error",
506 f"Unable to load authentication from {path}. "
507 "[Please login again](/config/cloud)",
508 )
509 _LOGGER.warning(
510 "Error loading cloud authentication info from %s: %s",
511 path,
512 err,
513 )
514 return None
515
516 return content
517
518 info = await self.run_executor(load_config)
519 if info is None:
520 # No previous token data
521 self.started = False
522 return
523
524 self.id_token = info["id_token"]
525 self.access_token = info["access_token"]
526 self.refresh_token = info["refresh_token"]
527
528 self._init_task = asyncio.create_task(self._finish_initialize())
529
530 async def _finish_initialize(self) -> None:
531 """Finish initializing the cloud component (load auth and maybe start)."""
532 try:
533 await self.auth.async_check_token()
534 except CloudError:
535 _LOGGER.debug("Failed to check cloud token", exc_info=True)
536
537 try:
538 await self.service_discovery.async_start_service_discovery()
539 except ServiceDiscoveryError as err:
540 _LOGGER.info("Failed to initialize service discovery: %s", err)
541
542 if await self.async_subscription_is_valid():
543 await self._start(skip_subscription_check=True)
544 await gather_callbacks(_LOGGER, "on_initialized", self._on_initialized)
545 self.started = True
546
547 self._init_task = None
548
549 async def _start(self, skip_subscription_check: bool = False) -> None:
550 """Start the cloud component."""
551 try:
552 await self.service_discovery.async_start_service_discovery()
553 except ServiceDiscoveryError as err:
554 _LOGGER.info("Failed to initialize service discovery: %s", err)
555
556 if skip_subscription_check or await self.async_subscription_is_valid():
557 await self.client.cloud_started()
558 await gather_callbacks(_LOGGER, "on_start", self._on_start)
559
560 async def stop(self) -> None:
561 """Stop the cloud component."""
562 if self._init_task:
563 self._init_task.cancel()
564 self._init_task = None
565
566 await self.service_discovery.async_stop_service_discovery()
567 await self.client.cloud_stopped()
568 await gather_callbacks(_LOGGER, "on_stop", self._on_stop)
569
570 @staticmethod
571 def _decode_claims(token: str) -> Mapping[str, Any]:
572 """Decode the claims in a token."""
573 decoded: Mapping[str, Any] = jwt.decode(
574 token,
575 options={"verify_signature": False},
576 )
577 return decoded
578
579 def async_initialize_subscription_reconnection_handler(
580 self,
581 reason: SubscriptionReconnectionReason,
582 ) -> None:
583 """Initialize the subscription reconnection handler."""
584 if self._subscription_reconnection_task is not None:
585 _LOGGER.debug("Subscription reconnection handler already running")
586 return
587
588 self._subscription_reconnection_task = asyncio.create_task(
589 self._subscription_reconnection_handler(reason),
590 name="subscription_reconnection_handler",
591 )
592
593 async def async_subscription_is_valid(self) -> bool:
594 """Verify that the subscription is valid."""
595 if self._subscription_reconnection_task is not None:
596 return False
597
598 if self.subscription_expired:
599 self.async_initialize_subscription_reconnection_handler(
600 SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED
601 )
602 return False
603
604 billing_plan_type: str | None = None
605
606 try:
607 async with asyncio.timeout(30):
608 subscription = await self.payments.subscription_info(skip_renew=True)
609 billing_plan_type = subscription.get("billing_plan_type")
610 except (CloudApiError, TimeoutError) as err:
611 _LOGGER.debug("Subscription validation failed - %s", err)
612 self.async_initialize_subscription_reconnection_handler(
613 SubscriptionReconnectionReason.CONNECTION_ERROR
614 )
615 return False
616 except NabuCasaBaseError as err:
617 _LOGGER.debug(err, exc_info=err)
618
619 if billing_plan_type is None or billing_plan_type == "no_subscription":
620 _LOGGER.info("No subscription found")
621 self.async_initialize_subscription_reconnection_handler(
622 SubscriptionReconnectionReason.NO_SUBSCRIPTION
623 )
624 return False
625 return True
626
627 async def _subscription_reconnection_handler(
628 self, reason: SubscriptionReconnectionReason
629 ) -> None:
630 """Handle subscription reconnection."""
631 issue_identifier = f"{reason.value}_{self.expiration_date}"
632 while True:
633 now_as_utc = utcnow()
634 sub_expired = self.expiration_date
635
636 if reason == SubscriptionReconnectionReason.CONNECTION_ERROR:
637 self._connection_retry_count += 1
638 base_wait = 0.01 + (
639 self._connection_retry_count * random.uniform(0.01, 0.09)
640 )
641 wait_hours = min(base_wait, 1.0)
642 elif sub_expired > (now_as_utc - timedelta(days=1)):
643 wait_hours = 3
644 elif sub_expired > (now_as_utc - timedelta(days=7)):
645 wait_hours = 12
646 elif sub_expired > (now_as_utc - timedelta(days=180)):
647 wait_hours = 24
648 elif sub_expired > (now_as_utc - timedelta(days=400)):
649 wait_hours = 96
650 else:
651 _LOGGER.info(
652 "Subscription expired at %s, not waiting for activation",
653 sub_expired.strftime("%Y-%m-%d"),
654 )
655 break
656
657 if reason == SubscriptionReconnectionReason.CONNECTION_ERROR:
658 _LOGGER.info(
659 "Could not establish connection (attempt %s), "
660 "waiting %s before retrying",
661 self._connection_retry_count,
662 seconds_as_dhms(wait_hours * 60 * 60),
663 )
664 await self.client.async_create_repair_issue(
665 identifier=issue_identifier,
666 translation_key=reason.value,
667 severity="warning",
668 )
669 else:
670 _LOGGER.info(
671 "Subscription expired at %s, waiting %s for activation",
672 sub_expired.strftime("%Y-%m-%d"),
673 seconds_as_dhms(wait_hours * 60 * 60),
674 )
675 await self.client.async_create_repair_issue(
676 identifier=issue_identifier,
677 translation_key=reason.value,
678 placeholders={"account_url": ACCOUNT_URL},
679 severity="error",
680 )
681
682 await asyncio.sleep(wait_hours * 60 * 60)
683
684 if not self.is_logged_in:
685 _LOGGER.info("No longer logged in, stopping reconnection handler")
686 break
687
688 try:
689 await self.auth.async_renew_access_token()
690 except CloudError as err:
691 _LOGGER.debug("Could not renew access token (%s)", err)
692 continue
693
694 if not self.subscription_expired:
695 await self.initialize()
696 break
697
698 await self.client.async_delete_repair_issue(identifier=issue_identifier)
699 _LOGGER.debug("Stopping subscription reconnection handler")
700 self._subscription_reconnection_task = None
701 self._connection_retry_count = 0