Debian Codegraph @

hass_nabucasa/remote.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Manage remote UI connections."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from contextvars import ContextVar
7 from datetime import datetime, timedelta
8 import logging
9 import random
10 from ssl import SSLContext, SSLError
11 from typing import TYPE_CHECKING, TypedDict
12
13 import aiohttp
14 import attr
15 from snitun.exceptions import SniTunConnectionError
16 from snitun.utils.aes import generate_aes_keyset
17 from snitun.utils.aiohttp_client import SniTunClientAioHttp
18
19 from . import const, utils
20 from .accounts_api import AccountsApiError
21 from .acme import AcmeClientError, AcmeHandler, AcmeJWSVerificationError
22 from .const import (
23 DISPATCH_CERTIFICATE_STATUS,
24 CertificateStatus,
25 SubscriptionReconnectionReason,
26 )
27 from .instance_api import InstanceApiError, PingResult
28
29 if TYPE_CHECKING:
30 from . import Cloud, _ClientT
31
32
33 _LOGGER = logging.getLogger(__name__)
34
35 RENEW_IF_EXPIRES_DAYS = 25
36 WARN_RENEW_FAILED_DAYS = 18
37
38 is_cloud_request = ContextVar("IS_CLOUD_REQUEST", default=False)
39
40
41 class RemoteError(Exception):
42 """General remote error."""
43
44
45 class RemoteBackendError(RemoteError):
46 """Backend problem with nabucasa API."""
47
48
49 class RemoteInsecureVersion(RemoteError):
50 """Raise if you try to connect with an insecure Core version."""
51
52
53 class RemoteForbidden(RemoteError):
54 """Raise if remote connection is not allowed."""
55
56
57 class RemoteNotConnected(RemoteError):
58 """Raise if a request need connection and we are not ready."""
59
60
61 class SubscriptionExpired(RemoteError):
62 """Raise if we cannot connect because subscription expired."""
63
64
65 class RemoteLatencyLocationResult(TypedDict):
66 """Latency results for a location."""
67
68 avg: float | None
69
70
71 @attr.s
72 class SniTunToken:
73 """Handle snitun token."""
74
75 fernet = attr.ib(type=bytes)
76 aes_key = attr.ib(type=bytes)
77 aes_iv = attr.ib(type=bytes)
78 valid = attr.ib(type=datetime)
79 throttling = attr.ib(type=int)
80
81
82 @attr.s
83 class Certificate:
84 """Handle certificate details."""
85
86 common_name = attr.ib(type=str)
87 expire_date = attr.ib(type=datetime)
88 fingerprint = attr.ib(type=str)
89 alternative_names = attr.ib(type=list[str] | None)
90
91
92 class RemoteUI:
93 """Class to help manage remote connections."""
94
95 def __init__(self, cloud: Cloud[_ClientT]) -> None:
96 """Initialize cloudhooks."""
97 self.cloud = cloud
98 self._acme: AcmeHandler | None = None
99 self._snitun: SniTunClientAioHttp | None = None
100 self._snitun_server: str | None = None
101 self._instance_domain: str | None = None
102 self._alias: list[str] | None = None
103 self._reconnect_task: asyncio.Task | None = None
104 self._acme_task: asyncio.Task | None = None
105 self._token: SniTunToken | None = None
106 self._certificate_status: CertificateStatus | None = None
107
108 self._results_by_location: dict[str, RemoteLatencyLocationResult] = {}
109
110 self._info_loaded = asyncio.Event()
111
112 # Register start/stop
113 cloud.register_on_start(self.start)
114 cloud.register_on_stop(self.stop)
115
116 async def start(self) -> None:
117 """Start remote UI loop."""
118 if self.cloud.subscription_expired:
119 self.cloud.async_initialize_subscription_reconnection_handler(
120 SubscriptionReconnectionReason.SUBSCRIPTION_EXPIRED,
121 )
122 return
123 self._acme_task = asyncio.create_task(self._certificate_handler())
124 await self._info_loaded.wait()
125
126 async def stop(self) -> None:
127 """Stop remote UI loop."""
128 if self._acme_task is None:
129 return
130
131 self._acme_task.cancel()
132 self._acme_task = None
133
134 @property
135 def snitun_server(self) -> str | None:
136 """Return connected snitun server."""
137 return self._snitun_server
138
139 @property
140 def certificate_status(self) -> CertificateStatus | None:
141 """Return the certificate status."""
142 return self._certificate_status
143
144 @property
145 def latency_by_location(self) -> dict[str, RemoteLatencyLocationResult]:
146 """Return latency results by location."""
147 return self._results_by_location
148
149 def _update_certificate_status(
150 self,
151 status: CertificateStatus,
152 ) -> None:
153 """Update certificate status and notify via dispatcher."""
154 if self._certificate_status == status:
155 return
156
157 self._certificate_status = status
158 _LOGGER.debug("Certificate status: %s", status)
159 self.cloud.client.dispatcher_message(DISPATCH_CERTIFICATE_STATUS, status)
160
161 @property
162 def instance_domain(self) -> str | None:
163 """Return instance domain."""
164 return self._instance_domain
165
166 @property
167 def alias(self) -> list[str] | None:
168 """Return alias."""
169 return self._alias
170
171 @property
172 def is_connected(self) -> bool:
173 """Return true if we are ready to connect."""
174 return bool(False if self._snitun is None else self._snitun.is_connected)
175
176 @property
177 def certificate(self) -> Certificate | None:
178 """Return certificate details."""
179 if (
180 not self._acme
181 or not self._acme.certificate_available
182 or self._acme.common_name is None
183 or self._acme.expire_date is None
184 or self._acme.fingerprint is None
185 ):
186 return None
187
188 return Certificate(
189 self._acme.common_name,
190 self._acme.expire_date,
191 self._acme.fingerprint,
192 alternative_names=self._acme.alternative_names,
193 )
194
195 async def _create_context(self) -> SSLContext:
196 """Create SSL context with acme certificate."""
197 context = utils.server_context_modern()
198
199 # We can not get here without this being set, but mypy does not know that.
200 assert self._acme is not None
201
202 await self.cloud.run_executor(
203 context.load_cert_chain,
204 self._acme.path_fullchain,
205 self._acme.path_private_key,
206 )
207
208 return context
209
210 async def _recreate_backend(self) -> None:
211 """There was a connection error, recreate the backend."""
212 _LOGGER.info("Recreating backend")
213 await self.close_backend()
214 # Wait until backend is cleaned
215 await asyncio.sleep(5)
216 await self.load_backend()
217
218 def _generate_acme_handler(self, *, domains: list[str], email: str) -> AcmeHandler:
219 """Generate a new ACME handler."""
220 return AcmeHandler(
221 self.cloud,
222 domains,
223 email,
224 status_callback=self._update_certificate_status,
225 )
226
227 async def _recreate_acme(self, domains: list[str], email: str) -> None:
228 """Recreate the acme client."""
229 if self._acme:
230 await self._acme.reset_acme()
231 self._acme = self._generate_acme_handler(domains=domains, email=email)
232
233 async def _fetch_ping_results(self) -> list[PingResult] | None:
234 """Fetch ping targets and measure latency.
235
236 Returns ping results or None if ping should be skipped or fails.
237 """
238 try:
239 async with asyncio.timeout(30):
240 ping_data = await self.cloud.instance.ping_targets()
241 except (TimeoutError, InstanceApiError) as err:
242 _LOGGER.warning("Unable to fetch ping targets: %s", err)
243 return None
244
245 if not (targets := ping_data.get("targets")):
246 _LOGGER.debug("No ping targets returned, skipping ping")
247 return None
248 target_by_ip = {target["ip"]: target for target in targets}
249
250 # The API returns timeout in milliseconds, but we need seconds.
251 timeout_seconds = ping_data["timeout"] / 1000
252 try:
253 latency_results = await utils.async_check_latency(
254 list(target_by_ip),
255 count=ping_data["count"],
256 ping_timeout=timeout_seconds,
257 privileged=self.cloud.privileged_ping,
258 )
259 except utils.CheckLatencyError as err:
260 _LOGGER.warning("Ping latency check failed: %s", err)
261 return None
262
263 self._results_by_location = {
264 target_by_ip[result["address"]]["location"]: RemoteLatencyLocationResult(
265 avg=result["avg_rtt"] if result["is_alive"] else None
266 )
267 for result in latency_results
268 }
269 _LOGGER.debug("Latency results by location: %s", self._results_by_location)
270
271 return [
272 PingResult(
273 ip=result["address"],
274 avg=result["avg_rtt"],
275 max=result["max_rtt"],
276 min=result["min_rtt"],
277 reachable=result["is_alive"],
278 )
279 for result in latency_results
280 ]
281
282 async def load_backend(self) -> bool:
283 """Load backend details."""
284 ping_result = await self._fetch_ping_results()
285
286 try:
287 async with asyncio.timeout(30):
288 data = await self.cloud.instance.register(ping_result=ping_result)
289 except (TimeoutError, InstanceApiError) as err:
290 msg = "Can't update remote details from Home Assistant cloud"
291 if isinstance(err, TimeoutError):
292 msg += " (timeout)"
293 else:
294 msg += f" ({err})"
295 _LOGGER.error(msg)
296 return False
297
298 # Extract data
299 _LOGGER.debug("Retrieved instance data: %s", data)
300
301 instance_domain = data["domain"]
302 email = data["email"]
303 server = data["server"]
304
305 # Cache data
306 self._instance_domain = instance_domain
307 self._snitun_server = server
308 self._alias = data.get("alias", [])
309
310 domains: list[str] = [instance_domain, *self._alias]
311
312 # Set instance details for certificate
313 self._acme = self._generate_acme_handler(domains=domains, email=email)
314
315 # Load exists certificate
316 self._update_certificate_status(CertificateStatus.LOADING)
317 await self._acme.load_certificate()
318
319 # Domain changed / revoke CA
320 ca_domains = set(self._acme.alternative_names or [])
321 if self._acme.common_name:
322 ca_domains.add(self._acme.common_name)
323
324 if not self._acme.certificate_available or (
325 ca_domains and ca_domains != set(domains)
326 ):
327 for alias in self.alias or []:
328 if not await self._custom_domain_dns_configuration_is_valid(
329 instance_domain, alias
330 ):
331 domains.remove(alias)
332
333 if ca_domains != set(domains):
334 if ca_domains:
335 _LOGGER.warning(
336 "Invalid certificate found for: (%s)",
337 ",".join(ca_domains),
338 )
339 await self._recreate_acme(domains, email)
340
341 self._info_loaded.set()
342
343 should_create_cert = await self._should_renew_certificates()
344
345 if should_create_cert:
346 try:
347 self._update_certificate_status(CertificateStatus.INITIAL_GENERATING)
348 await self._acme.issue_certificate()
349 except (AcmeJWSVerificationError, AcmeClientError) as err:
350 if isinstance(err, AcmeJWSVerificationError):
351 await self._recreate_acme(domains, email)
352 else:
353 _LOGGER.warning(
354 "Failed to issue certificate for %s: %s", ",".join(domains), err
355 )
356 self.cloud.client.user_message(
357 "cloud_remote_acme",
358 "Home Assistant Cloud",
359 const.MESSAGE_REMOTE_SETUP,
360 )
361 self._update_certificate_status(CertificateStatus.INITIAL_CERT_ERROR)
362 return False
363
364 self.cloud.client.user_message(
365 "cloud_remote_acme",
366 "Home Assistant Cloud",
367 const.MESSAGE_REMOTE_READY,
368 )
369
370 self._update_certificate_status(CertificateStatus.INITIAL_LOADED)
371 await self._acme.hardening_files()
372 self._update_certificate_status(CertificateStatus.READY)
373
374 if self.cloud.client.aiohttp_runner is None:
375 _LOGGER.debug("Waiting for aiohttp runner to come available")
376
377 # aiohttp_runner comes available when Home Assistant has started.
378 while self.cloud.client.aiohttp_runner is None: # noqa: ASYNC110
379 await asyncio.sleep(1)
380
381 try:
382 context = await self._create_context()
383 except SSLError as err:
384 if err.reason == "KEY_VALUES_MISMATCH":
385 self.cloud.client.user_message(
386 "cloud_remote_acme",
387 "Home Assistant Cloud",
388 const.MESSAGE_LOAD_CERTIFICATE_FAILURE,
389 )
390 await self._recreate_acme(domains, email)
391 self._update_certificate_status(CertificateStatus.SSL_CONTEXT_ERROR)
392 return False
393
394 # Setup snitun / aiohttp wrapper
395 _LOGGER.debug("Initializing SniTun")
396 self._snitun = SniTunClientAioHttp(
397 self.cloud.client.aiohttp_runner,
398 context,
399 snitun_server=self._snitun_server,
400 snitun_port=443,
401 )
402
403 _LOGGER.debug("Starting SniTun")
404 is_cloud_request.set(True)
405 await self._snitun.start(False, self._recreate_backend)
406 self.cloud.client.dispatcher_message(const.DISPATCH_REMOTE_BACKEND_UP)
407
408 _LOGGER.debug(
409 "Connecting remote backend: %s",
410 self.cloud.client.remote_autostart,
411 )
412 # Connect to remote is autostart enabled
413 if self.cloud.client.remote_autostart:
414 asyncio.create_task(self.connect())
415
416 return True
417
418 async def close_backend(self) -> None:
419 """Close connections and shutdown backend."""
420 _LOGGER.debug("Closing backend")
421
422 # Close reconnect task
423 if self._reconnect_task:
424 self._reconnect_task.cancel()
425 self._reconnect_task = None
426
427 # Disconnect snitun
428 if self._snitun:
429 await self._snitun.stop()
430
431 # Cleanup
432 self._snitun = None
433 self._acme = None
434 self._token = None
435 self._instance_domain = None
436 self._alias = None
437 self._snitun_server = None
438
439 self.cloud.client.dispatcher_message(const.DISPATCH_REMOTE_BACKEND_DOWN)
440
441 async def handle_connection_requests(self, caller_ip: str) -> None: # noqa: ARG002
442 """Handle connection requests."""
443 if not self._snitun:
444 raise RemoteNotConnected("Can't handle request-connection without backend")
445
446 if self._snitun.is_connected:
447 return
448 await self.connect()
449
450 async def _refresh_snitun_token(self) -> None:
451 """Handle snitun token."""
452 if self._token and self._token.valid > utils.utcnow():
453 _LOGGER.debug("Don't need refresh snitun token")
454 return
455
456 if self.cloud.subscription_expired:
457 raise SubscriptionExpired
458
459 # Generate session token
460 aes_key, aes_iv = generate_aes_keyset()
461 try:
462 async with asyncio.timeout(30):
463 data = await self.cloud.instance.snitun_token(
464 aes_key=aes_key, aes_iv=aes_iv
465 )
466 except TimeoutError:
467 raise RemoteBackendError from None
468 except InstanceApiError as err:
469 if err.status == 409:
470 raise RemoteInsecureVersion from err
471 if err.status == 403:
472 raise RemoteForbidden(err.reason or err) from err
473 raise RemoteBackendError from None
474 self._token = SniTunToken(
475 data["token"].encode(),
476 aes_key,
477 aes_iv,
478 utils.utc_from_timestamp(data["valid"]),
479 data["throttling"],
480 )
481
482 async def connect(self) -> None:
483 """Connect to snitun server."""
484 if not self._snitun:
485 raise RemoteNotConnected("Can't handle request-connection without backend")
486
487 # Check if we already connected
488 if self._snitun.is_connected:
489 return
490
491 insecure = False
492 forbidden = False
493 try:
494 _LOGGER.debug("Refresh snitun token")
495 async with asyncio.timeout(30):
496 await self._refresh_snitun_token()
497
498 # We can not get here without this being set, but mypy does not know that.
499 assert self._token is not None
500
501 _LOGGER.debug("Attempting connection to %s", self._snitun_server)
502 async with asyncio.timeout(30):
503 await self._snitun.connect(
504 self._token.fernet,
505 self._token.aes_key,
506 self._token.aes_iv,
507 throttling=self._token.throttling,
508 )
509 _LOGGER.debug("Connected")
510
511 self.cloud.client.dispatcher_message(const.DISPATCH_REMOTE_CONNECT)
512 except TimeoutError:
513 _LOGGER.error("Timeout connecting to snitun server")
514 except SniTunConnectionError as err:
515 _LOGGER.log(
516 logging.ERROR if self._reconnect_task is not None else logging.INFO,
517 "Connection problem to snitun server (%s)",
518 err,
519 )
520 except RemoteBackendError:
521 _LOGGER.error("Can't refresh the snitun token")
522 except RemoteForbidden as err:
523 _LOGGER.error("Remote connection is not allowed %s", err)
524 forbidden = True
525 except RemoteInsecureVersion:
526 self.cloud.client.user_message(
527 "connect_remote_insecure",
528 "Home Assistant Cloud error",
529 "Remote connection is disabled because this Home Assistant instance "
530 "is marked as insecure. For more information and to enable it again, "
531 "visit the [Nabu Casa Account page](https://account.nabucasa.com).",
532 )
533 insecure = True
534 except SubscriptionExpired:
535 pass
536 except AttributeError:
537 pass # Ignore because HA shutdown on snitun token refresh
538 finally:
539 # start retry task
540 if (
541 self._snitun
542 and not self._reconnect_task
543 and not (insecure or forbidden)
544 ):
545 self._reconnect_task = asyncio.create_task(self._reconnect_snitun())
546
547 # Disconnect if the instance is mark as insecure and we're in reconnect mode
548 elif self._reconnect_task and (insecure or forbidden):
549 asyncio.create_task(self.disconnect())
550
551 async def disconnect(self, clear_snitun_token: bool = False) -> None:
552 """Disconnect from snitun server."""
553 if not self._snitun:
554 raise RemoteNotConnected("Can't handle request-connection without backend")
555
556 # Stop reconnect task
557 if self._reconnect_task:
558 self._reconnect_task.cancel()
559
560 if clear_snitun_token:
561 self._token = None
562
563 # Check if we already connected
564 if not self._snitun.is_connected:
565 return
566 await self._snitun.disconnect()
567 self.cloud.client.dispatcher_message(const.DISPATCH_REMOTE_DISCONNECT)
568
569 async def _reconnect_snitun(self) -> None:
570 """Reconnect after disconnect."""
571 try:
572 while True:
573 if self._snitun is not None and self._snitun.is_connected:
574 await self._snitun.wait()
575
576 self.cloud.client.dispatcher_message(const.DISPATCH_REMOTE_DISCONNECT)
577 await asyncio.sleep(random.randint(1, 15))
578 await self.connect()
579 except asyncio.CancelledError:
580 pass
581 finally:
582 _LOGGER.debug("Close remote UI reconnect guard")
583 self._reconnect_task = None
584
585 async def _certificate_handler(self) -> None:
586 """Handle certification ACME Tasks."""
587 while True:
588 try:
589 if self._snitun:
590 _LOGGER.debug("Sleeping until tomorrow")
591 await asyncio.sleep(utils.next_midnight() + random.randint(1, 3600))
592
593 else:
594 _LOGGER.debug("Initializing backend")
595 if not await self.load_backend():
596 await asyncio.sleep(10)
597 continue
598
599 if TYPE_CHECKING:
600 assert self._acme is not None
601
602 # Renew certificate?
603 if not await self._should_renew_certificates():
604 self._update_certificate_status(CertificateStatus.READY)
605 continue
606
607 # Renew certificate
608 try:
609 _LOGGER.debug("Renewing certificate")
610 self._update_certificate_status(
611 CertificateStatus.RENEWAL_GENERATING
612 )
613 await self._acme.issue_certificate()
614 self._update_certificate_status(CertificateStatus.RENEWAL_LOADED)
615 await self._recreate_backend()
616 self._update_certificate_status(CertificateStatus.READY)
617 except AcmeClientError as err:
618 # Only log as warning if we have a certain amount of days left
619 if self._acme.expire_date is None or (
620 self._acme.expire_date
621 > utils.utcnow()
622 < (utils.utcnow() + timedelta(days=WARN_RENEW_FAILED_DAYS))
623 ):
624 meth = _LOGGER.warning
625 else:
626 meth = _LOGGER.debug
627
628 self._update_certificate_status(CertificateStatus.RENEWAL_FAILED)
629
630 meth(
631 "Renewal of ACME certificate failed. Trying again later: %s",
632 err,
633 )
634
635 except asyncio.CancelledError:
636 break
637
638 except Exception: # pylint: disable=broad-except
639 _LOGGER.exception("Unexpected error in Remote UI loop")
640 raise
641
642 _LOGGER.debug("Stopping Remote UI loop")
643 await self.close_backend()
644
645 async def _check_cname(self, hostname: str) -> list[str]:
646 """Get CNAME records for hostname."""
647 try:
648 return await self.cloud.accounts.instance_resolve_dns_cname(
649 hostname=hostname
650 )
651 except TimeoutError, aiohttp.ClientError, AccountsApiError:
652 _LOGGER.error("Can't resolve CNAME for %s", hostname)
653 return []
654
655 async def _custom_domain_dns_configuration_is_valid(
656 self,
657 instance_domain: str,
658 custom_domain: str,
659 ) -> bool:
660 """Validate custom domain."""
661 # Check primary entry
662 if instance_domain not in await self._check_cname(custom_domain):
663 return False
664
665 # Check LE entry
666 return f"_acme-challenge.{instance_domain}" in await self._check_cname(
667 f"_acme-challenge.{custom_domain}",
668 )
669
670 async def _should_renew_certificates(self) -> bool:
671 """Check if certificates should be renewed."""
672 self._update_certificate_status(CertificateStatus.VALIDATING)
673
674 if TYPE_CHECKING:
675 assert self._acme is not None
676 assert self.instance_domain is not None
677
678 if not self._acme.certificate_available:
679 self._update_certificate_status(CertificateStatus.NO_CERTIFICATE)
680 return True
681
682 utcnow = utils.utcnow()
683
684 if self._acme.expire_date is None or self._acme.expire_date <= utcnow:
685 self._update_certificate_status(CertificateStatus.EXPIRED)
686 return True
687
688 # Check if certificate is expiring soon
689 if self._acme.expire_date > (utcnow + timedelta(days=RENEW_IF_EXPIRES_DAYS)):
690 return False
691
692 self._update_certificate_status(CertificateStatus.EXPIRING_SOON)
693
694 check_alias = [
695 domain for domain in self._acme.domains if domain != self.instance_domain
696 ]
697
698 if not check_alias:
699 return True
700
701 # Check if defined alias is still valid:
702 bad_alias = []
703 for alias in check_alias:
704 if not await self._custom_domain_dns_configuration_is_valid(
705 self.instance_domain,
706 alias,
707 ):
708 bad_alias.append(alias) # noqa: PERF401
709
710 if not bad_alias:
711 # No bad configuration detected
712 return True
713
714 # Domain validation failed for some aliases
715 self._update_certificate_status(CertificateStatus.DOMAIN_VALIDATION_FAILED)
716
717 if self._acme.expire_date > (
718 utils.utcnow() + timedelta(days=WARN_RENEW_FAILED_DAYS)
719 ):
720 await self.cloud.client.async_create_repair_issue(
721 identifier=f"warn_bad_custom_domain_configuration_{self._acme.expire_date.timestamp()}",
722 translation_key="warn_bad_custom_domain_configuration",
723 placeholders={"custom_domains": ",".join(bad_alias)},
724 severity="warning",
725 )
726 return False
727
728 # Recreate the acme client with working domains
729 await self.cloud.client.async_create_repair_issue(
730 identifier=f"reset_bad_custom_domain_configuration_{self._acme.expire_date.timestamp()}",
731 translation_key="reset_bad_custom_domain_configuration",
732 placeholders={"custom_domains": ",".join(bad_alias)},
733 severity="error",
734 )
735
736 await self._recreate_acme(
737 [domain for domain in self._acme.domains if domain not in bad_alias],
738 self._acme.email,
739 )
740 return True
741
742 async def reset_acme(self) -> None:
743 """Reset the ACME client."""
744 if not self._acme:
745 return
746 await self._acme.reset_acme()