Debian Codegraph @

hass_nabucasa/remote.py

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