Debian Codegraph @

tests/test_remote.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """Test remote sni handler."""
2
3 import asyncio
4 from collections.abc import AsyncGenerator, Generator
5 from datetime import timedelta
6 from socket import gaierror
7 from ssl import SSLError
8 from typing import Any
9 from unittest.mock import Mock, patch
10
11 from acme import client, messages
12 import aiohttp
13 import pytest
14 from requests.exceptions import RequestException
15 from syrupy import SnapshotAssertion
16
17 from hass_nabucasa import Cloud, utils
18 from hass_nabucasa.accounts_api import AccountsApiError
19 from hass_nabucasa.acme import AcmeHandler
20 from hass_nabucasa.const import (
21 DISPATCH_CERTIFICATE_STATUS,
22 DISPATCH_REMOTE_BACKEND_DOWN,
23 DISPATCH_REMOTE_BACKEND_UP,
24 DISPATCH_REMOTE_CONNECT,
25 DISPATCH_REMOTE_DISCONNECT,
26 CertificateStatus,
27 )
28 from hass_nabucasa.remote import (
29 RENEW_IF_EXPIRES_DAYS,
30 WARN_RENEW_FAILED_DAYS,
31 SubscriptionExpired,
32 )
33 from hass_nabucasa.utils import utcnow
34 from tests.common import extract_log_messages
35 from tests.utils.aiohttp import AiohttpClientMocker
36
37 from .common import MockAcme, MockSnitun
38
39 # pylint: disable=protected-access
40
41
42 @pytest.fixture
43 def mock_timing() -> Generator[None]:
44 """Mock timing functions for remote tests."""
45 original_sleep = asyncio.sleep
46
47 async def mock_sleep(seconds: float) -> None:
48 """Mock sleep that only sleeps for very short time."""
49 await original_sleep(0.001)
50
51 with (
52 patch("hass_nabucasa.utils.next_midnight", return_value=0),
53 patch("random.randint", return_value=0),
54 patch("hass_nabucasa.remote.random.randint", return_value=0),
55 patch("hass_nabucasa.remote.asyncio.sleep", side_effect=mock_sleep),
56 ):
57 yield
58
59
60 @pytest.fixture(autouse=True)
61 def ignore_context() -> Generator[Mock]:
62 """Ignore ssl context."""
63 with patch(
64 "hass_nabucasa.remote.RemoteUI._create_context",
65 return_value=None,
66 ) as context:
67 yield context
68
69
70 @pytest.fixture
71 def acme_mock() -> Generator[MockAcme]:
72 """Mock ACME client."""
73 with patch("hass_nabucasa.remote.AcmeHandler", new_callable=MockAcme) as acme:
74 yield acme
75
76
77 @pytest.fixture
78 def valid_acme_mock(acme_mock: MockAcme) -> MockAcme:
79 """Mock ACME client with valid cert."""
80 acme_mock.common_name = "test.dui.nabu.casa"
81 acme_mock.alternative_names = ["test.dui.nabu.casa"]
82 acme_mock.expire_date = utcnow() + timedelta(days=60)
83 return acme_mock
84
85
86 @pytest.fixture
87 async def snitun_mock() -> AsyncGenerator[MockSnitun]:
88 """Mock ACME client."""
89 with patch("hass_nabucasa.remote.SniTunClientAioHttp", MockSnitun()) as snitun:
90 yield snitun
91
92
93 @pytest.fixture(autouse=True)
94 def mock_ping_targets(
95 aioclient_mock: AiohttpClientMocker,
96 cloud: Cloud,
97 ) -> None:
98 """Mock ping targets endpoint to return no targets by default."""
99 aioclient_mock.get(
100 f"https://{cloud.api_server}/instance/remote_ping_targets",
101 json={"targets": [], "timeout": 5000, "count": 1},
102 )
103
104
105 async def test_load_backend_exists_cert(
106 cloud: Cloud,
107 valid_acme_mock: MockAcme,
108 aioclient_mock: AiohttpClientMocker,
109 snitun_mock: MockSnitun,
110 ) -> None:
111 """Initialize backend."""
112 valid = utcnow() + timedelta(days=1)
113
114 aioclient_mock.post(
115 f"https://{cloud.api_server}/instance/register",
116 json={
117 "domain": "test.dui.nabu.casa",
118 "email": "[email protected]",
119 "server": "rest-remote.nabu.casa",
120 },
121 )
122 aioclient_mock.post(
123 f"https://{cloud.api_server}/instance/snitun_token",
124 json={
125 "token": "test-token",
126 "server": "rest-remote.nabu.casa",
127 "valid": valid.timestamp(),
128 "throttling": 400,
129 },
130 )
131
132 assert cloud.remote.certificate_status is None
133
134 assert not cloud.remote.is_connected
135 await cloud.remote.start()
136 await cloud.remote._info_loaded.wait()
137 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
138 assert cloud.remote.instance_domain == "test.dui.nabu.casa"
139
140 assert not valid_acme_mock.call_issue
141 assert valid_acme_mock.init_args == (
142 cloud,
143 ["test.dui.nabu.casa"],
144 "[email protected]",
145 )
146 assert valid_acme_mock.call_hardening
147 assert snitun_mock.call_start
148 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
149 assert snitun_mock.init_kwarg == {
150 "snitun_server": "rest-remote.nabu.casa",
151 "snitun_port": 443,
152 }
153
154 assert snitun_mock.start_whitelist is not None
155 assert snitun_mock.start_endpoint_connection_error_callback is not None
156
157 await asyncio.sleep(0.1)
158 assert snitun_mock.call_connect
159 assert snitun_mock.connect_args[0] == b"test-token"
160 assert snitun_mock.connect_args[3] == 400
161 assert cloud.remote.is_connected
162
163 assert cloud.remote._acme_task
164 assert cloud.remote._reconnect_task
165
166 # Check that certificate status updates were dispatched
167 certificate_dispatches = [
168 call
169 for call in cloud.client.mock_dispatcher
170 if call[0] == DISPATCH_CERTIFICATE_STATUS
171 ]
172 # Should have certificate status updates
173 assert len(certificate_dispatches) >= 1
174
175 # Check that backend and connection dispatches happened
176 backend_dispatches = [
177 call
178 for call in cloud.client.mock_dispatcher
179 if call[0] in (DISPATCH_REMOTE_BACKEND_UP, DISPATCH_REMOTE_CONNECT)
180 ]
181 assert any(call[0] == DISPATCH_REMOTE_BACKEND_UP for call in backend_dispatches)
182 assert any(call[0] == DISPATCH_REMOTE_CONNECT for call in backend_dispatches)
183
184 await cloud.remote.stop()
185 await asyncio.sleep(0.1)
186
187 assert not cloud.remote._acme_task
188 assert cloud.remote.certificate_status == CertificateStatus.READY
189
190
191 async def test_load_backend_not_exists_cert(
192 cloud: Cloud,
193 acme_mock: MockAcme,
194 aioclient_mock: AiohttpClientMocker,
195 snitun_mock: MockSnitun,
196 ) -> None:
197 """Initialize backend."""
198 valid = utcnow() + timedelta(days=1)
199
200 aioclient_mock.post(
201 f"https://{cloud.api_server}/instance/register",
202 json={
203 "domain": "test.dui.nabu.casa",
204 "email": "[email protected]",
205 "server": "rest-remote.nabu.casa",
206 },
207 )
208 aioclient_mock.post(
209 f"https://{cloud.api_server}/instance/snitun_token",
210 json={
211 "token": "test-token",
212 "server": "rest-remote.nabu.casa",
213 "valid": valid.timestamp(),
214 "throttling": 400,
215 },
216 )
217
218 acme_mock.set_false()
219 await cloud.remote.start()
220 await asyncio.sleep(0.1)
221
222 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
223 assert acme_mock.call_issue
224 assert acme_mock.init_args == (
225 cloud,
226 ["test.dui.nabu.casa"],
227 "[email protected]",
228 )
229 assert acme_mock.call_hardening
230 assert snitun_mock.call_start
231 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
232 assert snitun_mock.init_kwarg == {
233 "snitun_server": "rest-remote.nabu.casa",
234 "snitun_port": 443,
235 }
236
237 assert snitun_mock.call_connect
238 assert snitun_mock.connect_args[0] == b"test-token"
239 assert snitun_mock.connect_args[3] == 400
240
241 assert cloud.remote._acme_task
242 assert cloud.remote._reconnect_task
243
244 await cloud.remote.stop()
245 await asyncio.sleep(0.1)
246
247 assert not cloud.remote._acme_task
248
249
250 async def test_load_and_unload_backend(
251 cloud: Cloud,
252 valid_acme_mock: MockAcme,
253 aioclient_mock: AiohttpClientMocker,
254 snitun_mock: MockSnitun,
255 mock_timing: None,
256 ) -> None:
257 """Initialize backend."""
258 valid = utcnow() + timedelta(days=1)
259
260 aioclient_mock.post(
261 f"https://{cloud.api_server}/instance/register",
262 json={
263 "domain": "test.dui.nabu.casa",
264 "email": "[email protected]",
265 "server": "rest-remote.nabu.casa",
266 },
267 )
268 aioclient_mock.post(
269 f"https://{cloud.api_server}/instance/snitun_token",
270 json={
271 "token": "test-token",
272 "server": "rest-remote.nabu.casa",
273 "valid": valid.timestamp(),
274 "throttling": 400,
275 },
276 )
277
278 await cloud.remote.start()
279 await asyncio.sleep(0.1)
280
281 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
282 assert not valid_acme_mock.call_issue
283 assert valid_acme_mock.init_args == (
284 cloud,
285 ["test.dui.nabu.casa"],
286 "[email protected]",
287 )
288 assert valid_acme_mock.call_hardening
289 assert snitun_mock.call_start
290 assert not snitun_mock.call_stop
291 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
292 assert snitun_mock.init_kwarg == {
293 "snitun_server": "rest-remote.nabu.casa",
294 "snitun_port": 443,
295 }
296
297 assert cloud.remote._acme_task
298 assert cloud.remote._reconnect_task
299
300 await cloud.remote.stop()
301 await asyncio.sleep(0.1)
302
303 assert snitun_mock.call_stop
304
305 assert not cloud.remote._acme_task
306 assert not cloud.remote._reconnect_task
307
308 assert cloud.client.mock_dispatcher[-1][0] == DISPATCH_REMOTE_BACKEND_DOWN
309
310
311 async def test_load_backend_exists_wrong_cert(
312 cloud: Cloud,
313 valid_acme_mock: MockAcme,
314 aioclient_mock: AiohttpClientMocker,
315 snitun_mock: MockSnitun,
316 mock_timing: None,
317 ) -> None:
318 """Initialize backend."""
319 valid = utcnow() + timedelta(days=1)
320
321 aioclient_mock.post(
322 f"https://{cloud.api_server}/instance/register",
323 json={
324 "domain": "test.dui.nabu.casa",
325 "email": "[email protected]",
326 "server": "rest-remote.nabu.casa",
327 "alias": ["example.com"],
328 },
329 )
330 aioclient_mock.post(
331 f"https://{cloud.api_server}/instance/snitun_token",
332 json={
333 "token": "test-token",
334 "server": "rest-remote.nabu.casa",
335 "valid": valid.timestamp(),
336 "throttling": 400,
337 },
338 )
339
340 aioclient_mock.post(
341 f"https://{cloud.api_server}/account/instance/resolve_dns_cname",
342 json=[
343 "test.dui.nabu.casa",
344 "_acme-challenge.test.dui.nabu.casa",
345 ],
346 )
347
348 valid_acme_mock.common_name = "test.dui.nabu.casa"
349 valid_acme_mock.alternative_names = ["test.dui.nabu.casa"]
350 await cloud.remote.load_backend()
351 await asyncio.sleep(0.1)
352
353 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
354 assert valid_acme_mock.call_reset
355 assert valid_acme_mock.init_args == (
356 cloud,
357 ["test.dui.nabu.casa", "example.com"],
358 "[email protected]",
359 )
360 assert valid_acme_mock.call_hardening
361 assert snitun_mock.call_start
362 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
363 assert snitun_mock.init_kwarg == {
364 "snitun_server": "rest-remote.nabu.casa",
365 "snitun_port": 443,
366 }
367
368 assert snitun_mock.call_connect
369 assert snitun_mock.connect_args[0] == b"test-token"
370 assert snitun_mock.connect_args[3] == 400
371
372 await cloud.remote.disconnect()
373 await asyncio.sleep(0.1)
374
375 assert snitun_mock.call_disconnect
376
377
378 async def test_call_disconnect(
379 cloud: Cloud,
380 acme_mock: MockAcme,
381 aioclient_mock: AiohttpClientMocker,
382 snitun_mock: MockSnitun,
383 mock_timing: None,
384 ) -> None:
385 """Initialize backend."""
386 valid = utcnow() + timedelta(days=1)
387
388 aioclient_mock.post(
389 f"https://{cloud.api_server}/instance/register",
390 json={
391 "domain": "test.dui.nabu.casa",
392 "email": "[email protected]",
393 "server": "rest-remote.nabu.casa",
394 },
395 )
396 aioclient_mock.post(
397 f"https://{cloud.api_server}/instance/snitun_token",
398 json={
399 "token": "test-token",
400 "server": "rest-remote.nabu.casa",
401 "valid": valid.timestamp(),
402 "throttling": 400,
403 },
404 )
405
406 assert not cloud.remote.is_connected
407 await cloud.remote.load_backend()
408 await asyncio.sleep(0.1)
409 assert cloud.remote.is_connected
410
411 await cloud.remote.disconnect()
412 assert snitun_mock.call_disconnect
413 assert not cloud.remote.is_connected
414 assert cloud.remote._token
415 assert cloud.client.mock_dispatcher[-1][0] == DISPATCH_REMOTE_DISCONNECT
416
417
418 async def test_load_backend_no_autostart(
419 cloud: Cloud,
420 valid_acme_mock: MockAcme,
421 aioclient_mock: AiohttpClientMocker,
422 snitun_mock: MockSnitun,
423 mock_timing: None,
424 ) -> None:
425 """Initialize backend."""
426 valid = utcnow() + timedelta(days=1)
427
428 aioclient_mock.post(
429 f"https://{cloud.api_server}/instance/register",
430 json={
431 "domain": "test.dui.nabu.casa",
432 "email": "[email protected]",
433 "server": "rest-remote.nabu.casa",
434 },
435 )
436 aioclient_mock.post(
437 f"https://{cloud.api_server}/instance/snitun_token",
438 json={
439 "token": "test-token",
440 "server": "rest-remote.nabu.casa",
441 "valid": valid.timestamp(),
442 "throttling": 400,
443 },
444 )
445
446 cloud.client.prop_remote_autostart = False
447 await cloud.remote.load_backend()
448 await asyncio.sleep(0.1)
449
450 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
451 assert not valid_acme_mock.call_issue
452 assert valid_acme_mock.call_hardening
453 assert snitun_mock.call_start
454
455 assert not snitun_mock.call_connect
456
457 await cloud.remote.connect()
458
459 assert snitun_mock.call_connect
460 assert snitun_mock.connect_args[0] == b"test-token"
461 assert snitun_mock.connect_args[3] == 400
462 assert cloud.client.mock_dispatcher[-1][0] == DISPATCH_REMOTE_CONNECT
463
464 await cloud.remote.disconnect()
465 await asyncio.sleep(0.1)
466
467 assert snitun_mock.call_disconnect
468
469
470 async def test_get_certificate_details(
471 cloud: Cloud,
472 acme_mock: MockAcme,
473 aioclient_mock: AiohttpClientMocker,
474 snitun_mock: MockSnitun,
475 mock_timing: None,
476 ) -> None:
477 """Initialize backend."""
478 valid = utcnow() + timedelta(days=1)
479
480 assert cloud.remote.certificate is None
481
482 aioclient_mock.post(
483 f"https://{cloud.api_server}/instance/register",
484 json={
485 "domain": "test.dui.nabu.casa",
486 "email": "[email protected]",
487 "server": "rest-remote.nabu.casa",
488 },
489 )
490 aioclient_mock.post(
491 f"https://{cloud.api_server}/instance/snitun_token",
492 json={
493 "token": "test-token",
494 "server": "rest-remote.nabu.casa",
495 "valid": valid.timestamp(),
496 "throttling": 400,
497 },
498 )
499
500 cloud.client.prop_remote_autostart = False
501 await cloud.remote.load_backend()
502 await asyncio.sleep(0.1)
503 assert cloud.remote.certificate is None
504
505 acme_mock.common_name = "test"
506 acme_mock.alternative_names = ["test"]
507 acme_mock.expire_date = valid
508 acme_mock.fingerprint = "ffff"
509
510 certificate = cloud.remote.certificate
511 assert certificate.common_name == "test"
512 assert certificate.alternative_names == ["test"]
513 assert certificate.expire_date == valid
514 assert certificate.fingerprint == "ffff"
515
516
517 async def test_certificate_task_no_backend(
518 cloud: Cloud,
519 acme_mock: MockAcme,
520 aioclient_mock: AiohttpClientMocker,
521 snitun_mock: MockSnitun,
522 mock_timing: None,
523 ) -> None:
524 """Initialize backend."""
525 valid = utcnow() + timedelta(days=1)
526
527 aioclient_mock.post(
528 f"https://{cloud.api_server}/instance/register",
529 json={
530 "domain": "test.dui.nabu.casa",
531 "email": "[email protected]",
532 "server": "rest-remote.nabu.casa",
533 },
534 )
535 aioclient_mock.post(
536 f"https://{cloud.api_server}/instance/snitun_token",
537 json={
538 "token": "test-token",
539 "server": "rest-remote.nabu.casa",
540 "valid": valid.timestamp(),
541 "throttling": 400,
542 },
543 )
544
545 acme_mock.expire_date = valid
546
547 with (
548 patch("hass_nabucasa.utils.next_midnight", return_value=0),
549 patch("random.randint", return_value=0),
550 ):
551 acme_task = cloud.remote._acme_task = asyncio.create_task(
552 cloud.remote._certificate_handler(),
553 )
554 await asyncio.sleep(0.1)
555 assert acme_mock.call_issue
556 assert snitun_mock.call_start
557
558 await cloud.remote.stop()
559 await asyncio.sleep(0.1)
560
561 assert acme_task.done()
562
563
564 async def test_certificate_task_renew_cert(
565 cloud: Cloud,
566 acme_mock: MockAcme,
567 aioclient_mock: AiohttpClientMocker,
568 snitun_mock: MockSnitun,
569 mock_timing: None,
570 ) -> None:
571 """Initialize backend."""
572 valid = utcnow() + timedelta(days=1)
573
574 aioclient_mock.post(
575 f"https://{cloud.api_server}/instance/register",
576 json={
577 "domain": "test.dui.nabu.casa",
578 "email": "[email protected]",
579 "server": "rest-remote.nabu.casa",
580 },
581 )
582 aioclient_mock.post(
583 f"https://{cloud.api_server}/instance/snitun_token",
584 json={
585 "token": "test-token",
586 "server": "rest-remote.nabu.casa",
587 "valid": valid.timestamp(),
588 "throttling": 400,
589 },
590 )
591
592 acme_mock.expire_date = utcnow() + timedelta(days=-40)
593
594 with (
595 patch("hass_nabucasa.utils.next_midnight", return_value=0),
596 patch("random.randint", return_value=0),
597 ):
598 acme_task = cloud.remote._acme_task = asyncio.create_task(
599 cloud.remote._certificate_handler(),
600 )
601
602 await cloud.remote.load_backend()
603 await asyncio.sleep(0.1)
604 assert acme_mock.call_issue
605
606 await cloud.remote.stop()
607 await asyncio.sleep(0.1)
608
609 assert acme_task.done()
610
611
612 async def test_refresh_token_no_sub(cloud: Cloud, mock_timing: None) -> None:
613 """Test that we rais SubscriptionExpired if expired sub."""
614 with (
615 patch.object(
616 type(cloud),
617 "subscription_expired",
618 new_callable=lambda: property(lambda _: True),
619 ),
620 pytest.raises(SubscriptionExpired),
621 ):
622 await cloud.remote._refresh_snitun_token()
623
624
625 async def test_load_connect_insecure(
626 cloud: Cloud,
627 valid_acme_mock: MockAcme,
628 aioclient_mock: AiohttpClientMocker,
629 snitun_mock: MockSnitun,
630 caplog: pytest.LogCaptureFixture,
631 snapshot: SnapshotAssertion,
632 mock_timing: None,
633 ) -> None:
634 """Initialize backend."""
635 valid = utcnow() + timedelta(days=1)
636
637 # Mock the error response via aioclient_mock instead
638
639 aioclient_mock.post(
640 f"https://{cloud.api_server}/instance/register",
641 json={
642 "domain": "test.dui.nabu.casa",
643 "email": "[email protected]",
644 "server": "rest-remote.nabu.casa",
645 },
646 )
647 aioclient_mock.post(
648 f"https://{cloud.api_server}/instance/snitun_token",
649 json={
650 "token": "test-token",
651 "server": "rest-remote.nabu.casa",
652 "valid": valid.timestamp(),
653 "throttling": 400,
654 },
655 status=409,
656 )
657
658 cloud.client.prop_remote_autostart = True
659 await cloud.remote.load_backend()
660 await asyncio.sleep(0.1)
661
662 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
663 assert not valid_acme_mock.call_issue
664 assert valid_acme_mock.call_hardening
665 assert snitun_mock.call_start
666
667 assert not snitun_mock.call_connect
668
669 assert not snitun_mock.call_connect
670 assert cloud.client.mock_dispatcher[-1][0] == DISPATCH_REMOTE_BACKEND_UP
671
672 assert snapshot == extract_log_messages(caplog)
673
674
675 async def test_load_connect_forbidden(
676 cloud: Cloud,
677 valid_acme_mock: MockAcme,
678 aioclient_mock: AiohttpClientMocker,
679 snitun_mock: MockSnitun,
680 caplog: pytest.LogCaptureFixture,
681 snapshot: SnapshotAssertion,
682 mock_timing: None,
683 ) -> None:
684 """Initialize backend."""
685 # Mock the error response via aioclient_mock instead
686
687 aioclient_mock.post(
688 f"https://{cloud.api_server}/instance/register",
689 json={
690 "domain": "test.dui.nabu.casa",
691 "email": "[email protected]",
692 "server": "rest-remote.nabu.casa",
693 },
694 )
695 aioclient_mock.post(
696 f"https://{cloud.api_server}/instance/snitun_token",
697 json={
698 "message": "lorem_ipsum",
699 },
700 status=403,
701 headers={"content-type": "application/json; charset=utf-8"},
702 )
703
704 cloud.client.prop_remote_autostart = True
705 await cloud.remote.load_backend()
706 await asyncio.sleep(0.1)
707
708 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
709 assert not valid_acme_mock.call_issue
710 assert valid_acme_mock.call_hardening
711 assert snitun_mock.call_start
712 assert not snitun_mock.call_connect
713
714 assert snapshot == extract_log_messages(caplog)
715
716
717 async def test_call_disconnect_clean_token(
718 cloud: Cloud,
719 acme_mock: MockAcme,
720 aioclient_mock: AiohttpClientMocker,
721 snitun_mock: MockSnitun,
722 mock_timing: None,
723 ) -> None:
724 """Initialize backend."""
725 valid = utcnow() + timedelta(days=1)
726
727 aioclient_mock.post(
728 f"https://{cloud.api_server}/instance/register",
729 json={
730 "domain": "test.dui.nabu.casa",
731 "email": "[email protected]",
732 "server": "rest-remote.nabu.casa",
733 },
734 )
735 aioclient_mock.post(
736 f"https://{cloud.api_server}/instance/snitun_token",
737 json={
738 "token": "test-token",
739 "server": "rest-remote.nabu.casa",
740 "valid": valid.timestamp(),
741 "throttling": 400,
742 },
743 )
744
745 assert not cloud.remote.is_connected
746 await cloud.remote.load_backend()
747 await asyncio.sleep(0.1)
748 assert cloud.remote.is_connected
749 assert cloud.remote._token
750
751 await cloud.remote.disconnect(clear_snitun_token=True)
752 assert snitun_mock.call_disconnect
753 assert not cloud.remote.is_connected
754 assert cloud.remote._token is None
755 assert cloud.client.mock_dispatcher[-1][0] == DISPATCH_REMOTE_DISCONNECT
756
757
758 async def test_recreating_old_certificate_with_bad_dns_config(
759 cloud: Cloud,
760 valid_acme_mock: MockAcme,
761 aioclient_mock: AiohttpClientMocker,
762 snitun_mock: MockSnitun,
763 caplog: pytest.LogCaptureFixture,
764 snapshot: SnapshotAssertion,
765 mock_timing: None,
766 ) -> None:
767 """Test recreating old certificate with bad DNS config for alias."""
768 valid = utcnow() + timedelta(days=1)
769
770 aioclient_mock.post(
771 f"https://{cloud.api_server}/instance/register",
772 json={
773 "domain": "test.dui.nabu.casa",
774 "email": "[email protected]",
775 "server": "rest-remote.nabu.casa",
776 "alias": ["example.com"],
777 },
778 )
779 aioclient_mock.post(
780 f"https://{cloud.api_server}/instance/snitun_token",
781 json={
782 "token": "test-token",
783 "server": "rest-remote.nabu.casa",
784 "valid": valid.timestamp(),
785 "throttling": 400,
786 },
787 )
788 aioclient_mock.post(
789 f"https://{cloud.api_server}/account/instance/resolve_dns_cname",
790 json=["test.dui.nabu.casa"],
791 )
792
793 valid_acme_mock.common_name = "test.dui.nabu.casa"
794 valid_acme_mock.alternative_names = ["test.dui.nabu.casa", "example.com"]
795 valid_acme_mock.expire_date = utils.utcnow() + timedelta(
796 days=WARN_RENEW_FAILED_DAYS,
797 )
798 await cloud.remote.load_backend()
799 await asyncio.sleep(0.1)
800
801 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
802 assert valid_acme_mock.call_reset
803 assert valid_acme_mock.init_args == (
804 cloud,
805 ["test.dui.nabu.casa"],
806 "[email protected]",
807 )
808 assert valid_acme_mock.call_hardening
809 assert snitun_mock.call_start
810 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
811 assert snitun_mock.init_kwarg == {
812 "snitun_server": "rest-remote.nabu.casa",
813 "snitun_port": 443,
814 }
815
816 assert snapshot == cloud.client.mock_repairs
817
818 assert snitun_mock.call_connect
819 assert snitun_mock.connect_args[0] == b"test-token"
820 assert snitun_mock.connect_args[3] == 400
821
822 await cloud.remote.disconnect()
823 await asyncio.sleep(0.1)
824
825 assert snitun_mock.call_disconnect
826
827
828 @pytest.mark.parametrize(
829 "exception",
830 (
831 AccountsApiError("DNS resolution failed"),
832 aiohttp.ClientError("DNS resolution failed"),
833 TimeoutError(),
834 ),
835 )
836 async def test_warn_about_bad_dns_config_for_old_certificate(
837 cloud: Cloud,
838 valid_acme_mock: MockAcme,
839 aioclient_mock: AiohttpClientMocker,
840 snitun_mock: MockSnitun,
841 caplog: pytest.LogCaptureFixture,
842 snapshot: SnapshotAssertion,
843 mock_timing: None,
844 exception: Exception,
845 ) -> None:
846 """Test warn about old certificate with bad DNS config for alias."""
847 valid = utcnow() + timedelta(days=1)
848
849 aioclient_mock.post(
850 f"https://{cloud.api_server}/instance/register",
851 json={
852 "domain": "test.dui.nabu.casa",
853 "email": "[email protected]",
854 "server": "rest-remote.nabu.casa",
855 "alias": ["example.com"],
856 },
857 )
858 aioclient_mock.post(
859 f"https://{cloud.api_server}/instance/snitun_token",
860 json={
861 "token": "test-token",
862 "server": "rest-remote.nabu.casa",
863 "valid": valid.timestamp(),
864 "throttling": 400,
865 },
866 )
867 aioclient_mock.post(
868 f"https://{cloud.api_server}/account/instance/resolve_dns_cname",
869 exc=exception,
870 )
871
872 valid_acme_mock.common_name = "test.dui.nabu.casa"
873 valid_acme_mock.alternative_names = ["test.dui.nabu.casa", "example.com"]
874 valid_acme_mock.expire_date = utils.utcnow() + timedelta(days=RENEW_IF_EXPIRES_DAYS)
875 await cloud.remote.load_backend()
876 await asyncio.sleep(0.1)
877
878 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
879 assert not valid_acme_mock.call_reset
880 assert snitun_mock.call_start
881 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
882 assert snitun_mock.init_kwarg == {
883 "snitun_server": "rest-remote.nabu.casa",
884 "snitun_port": 443,
885 }
886
887 assert snapshot == cloud.client.mock_repairs
888
889 assert snitun_mock.call_connect
890 assert snitun_mock.connect_args[0] == b"test-token"
891 assert snitun_mock.connect_args[3] == 400
892
893 await cloud.remote.disconnect()
894 await asyncio.sleep(0.1)
895
896 assert snitun_mock.call_disconnect
897
898
899 async def test_regeneration_without_warning_for_good_dns_config(
900 cloud: Cloud,
901 valid_acme_mock: MockAcme,
902 aioclient_mock: AiohttpClientMocker,
903 snitun_mock: MockSnitun,
904 snapshot: SnapshotAssertion,
905 mock_timing: None,
906 ) -> None:
907 """Test no warning for good dns config."""
908 valid = utcnow() + timedelta(days=1)
909
910 aioclient_mock.post(
911 f"https://{cloud.api_server}/instance/register",
912 json={
913 "domain": "test.dui.nabu.casa",
914 "email": "[email protected]",
915 "server": "rest-remote.nabu.casa",
916 "alias": ["example.com"],
917 },
918 )
919 aioclient_mock.post(
920 f"https://{cloud.api_server}/instance/snitun_token",
921 json={
922 "token": "test-token",
923 "server": "rest-remote.nabu.casa",
924 "valid": valid.timestamp(),
925 "throttling": 400,
926 },
927 )
928 aioclient_mock.post(
929 f"https://{cloud.api_server}/account/instance/resolve_dns_cname",
930 json=[
931 "test.dui.nabu.casa",
932 "_acme-challenge.test.dui.nabu.casa",
933 ],
934 )
935
936 valid_acme_mock.common_name = "test.dui.nabu.casa"
937 valid_acme_mock.alternative_names = ["test.dui.nabu.casa", "example.com"]
938 valid_acme_mock.expire_date = utils.utcnow() + timedelta(days=RENEW_IF_EXPIRES_DAYS)
939 await cloud.remote.load_backend()
940 await asyncio.sleep(0.1)
941
942 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
943 assert not valid_acme_mock.call_reset
944 assert valid_acme_mock.call_issue
945 assert snitun_mock.call_start
946 assert snitun_mock.init_args == (cloud.client.aiohttp_runner, None)
947 assert snitun_mock.init_kwarg == {
948 "snitun_server": "rest-remote.nabu.casa",
949 "snitun_port": 443,
950 }
951
952 assert snapshot == cloud.client.mock_repairs
953
954 assert snitun_mock.call_connect
955 assert snitun_mock.connect_args[0] == b"test-token"
956 assert snitun_mock.connect_args[3] == 400
957
958 await cloud.remote.disconnect()
959 await asyncio.sleep(0.1)
960
961 assert snitun_mock.call_disconnect
962
963
964 @pytest.mark.parametrize(
965 ("json_error", "should_reset"),
966 (
967 (
968 {
969 "type": "urn:ietf:params:acme:error:malformed",
970 "detail": "JWS verification error",
971 },
972 True,
973 ),
974 (
975 {
976 "type": "urn:ietf:params:acme:error:malformed",
977 "detail": "Unable to validate JWS",
978 },
979 True,
980 ),
981 (
982 {
983 "type": "urn:ietf:params:acme:error:malformed",
984 "detail": "Unable to validate JWS :: Invalid Content-Type header on",
985 },
986 True,
987 ),
988 (
989 {
990 "type": "urn:ietf:params:acme:error:malformed",
991 "detail": "Some other malformed reason",
992 },
993 False,
994 ),
995 (
996 {
997 "type": "about:blank",
998 "detail": "Boom",
999 },
1000 False,
1001 ),
1002 ),
1003 )
1004 async def test_acme_client_new_order_errors(
1005 cloud: Cloud,
1006 aioclient_mock: AiohttpClientMocker,
1007 snitun_mock: MockSnitun,
1008 json_error: dict[str, str],
1009 should_reset: bool,
1010 caplog: pytest.LogCaptureFixture,
1011 snapshot: SnapshotAssertion,
1012 mock_timing: None,
1013 ) -> None:
1014 """Initialize backend."""
1015
1016 class _MockAcmeClient(client.ClientV2):
1017 def __init__(self) -> None:
1018 pass
1019
1020 def new_order(self, _: Any) -> None:
1021 raise messages.Error.from_json(json_error)
1022
1023 class _MockAcme(AcmeHandler):
1024 call_reset: bool = False
1025 # cloud instance passed via constructor
1026
1027 @property
1028 def certificate_available(self) -> bool:
1029 return True
1030
1031 @property
1032 def alternative_names(self) -> list[str]:
1033 return ["test.dui.nabu.casa"]
1034
1035 def _generate_csr(self) -> bytes:
1036 return b""
1037
1038 def _create_client(self) -> None:
1039 self._acme_client = _MockAcmeClient()
1040
1041 async def reset_acme(self) -> None:
1042 self.call_reset = True
1043
1044 aioclient_mock.post(
1045 f"https://{cloud.api_server}/instance/register",
1046 json={
1047 "domain": "test.dui.nabu.casa",
1048 "email": "[email protected]",
1049 "server": "rest-remote.nabu.casa",
1050 },
1051 )
1052
1053 with patch(
1054 "hass_nabucasa.remote.AcmeHandler",
1055 return_value=_MockAcme(cloud, [], "[email protected]", Mock()),
1056 ):
1057 assert cloud.remote._certificate_status is None
1058 await cloud.remote.load_backend()
1059
1060 await asyncio.sleep(0.1)
1061 assert cloud.remote._acme.call_reset == should_reset
1062 assert cloud.remote._certificate_status is CertificateStatus.INITIAL_CERT_ERROR
1063
1064 assert snapshot == extract_log_messages(caplog)
1065
1066 await cloud.remote.stop()
1067
1068
1069 @pytest.mark.parametrize(
1070 ("json_error", "should_reset"),
1071 (
1072 (
1073 {
1074 "type": "urn:ietf:params:acme:error:malformed",
1075 "detail": "JWS verification error",
1076 },
1077 True,
1078 ),
1079 (
1080 {
1081 "type": "urn:ietf:params:acme:error:malformed",
1082 "detail": "Unable to validate JWS",
1083 },
1084 True,
1085 ),
1086 (
1087 {
1088 "type": "urn:ietf:params:acme:error:malformed",
1089 "detail": "Unable to validate JWS :: Invalid Content-Type header on",
1090 },
1091 True,
1092 ),
1093 (
1094 {
1095 "type": "urn:ietf:params:acme:error:malformed",
1096 "detail": "Some other malformed reason",
1097 },
1098 False,
1099 ),
1100 (
1101 {
1102 "type": "about:blank",
1103 "detail": "Boom",
1104 },
1105 False,
1106 ),
1107 ),
1108 )
1109 async def test_acme_client_create_client_jws_errors(
1110 cloud: Cloud,
1111 aioclient_mock: AiohttpClientMocker,
1112 snitun_mock: MockSnitun,
1113 json_error: dict[str, str],
1114 should_reset: bool,
1115 caplog: pytest.LogCaptureFixture,
1116 snapshot: SnapshotAssertion,
1117 mock_timing: None,
1118 ) -> None:
1119 """Test ACME client creation JWS error handling."""
1120
1121 class _MockAcmeClient(client.ClientV2):
1122 def __init__(self) -> None:
1123 pass
1124
1125 @classmethod
1126 def get_directory(cls, *_: Any, **_kwargs: Any) -> None:
1127 raise messages.Error.from_json(json_error)
1128
1129 class _MockAcme(AcmeHandler):
1130 call_reset: bool = False
1131 # cloud instance passed via constructor
1132
1133 @property
1134 def certificate_available(self) -> bool:
1135 return True
1136
1137 @property
1138 def alternative_names(self) -> list[str]:
1139 return ["test.dui.nabu.casa"]
1140
1141 def _load_account_key(self) -> None:
1142 self._account_jwk = Mock()
1143
1144 def _create_client(self) -> None:
1145 with patch("hass_nabucasa.acme.client.ClientV2", _MockAcmeClient):
1146 super()._create_client()
1147
1148 async def reset_acme(self) -> None:
1149 self.call_reset = True
1150
1151 aioclient_mock.post(
1152 f"https://{cloud.api_server}/instance/register",
1153 json={
1154 "domain": "test.dui.nabu.casa",
1155 "email": "[email protected]",
1156 "server": "rest-remote.nabu.casa",
1157 },
1158 )
1159
1160 with patch(
1161 "hass_nabucasa.remote.AcmeHandler",
1162 return_value=_MockAcme(cloud, [], "[email protected]", Mock()),
1163 ):
1164 assert cloud.remote._certificate_status is None
1165 await cloud.remote.load_backend()
1166
1167 await asyncio.sleep(0.1)
1168 assert cloud.remote._acme.call_reset == should_reset
1169 assert cloud.remote._certificate_status is CertificateStatus.INITIAL_CERT_ERROR
1170
1171 assert snapshot == extract_log_messages(caplog)
1172
1173 await cloud.remote.stop()
1174
1175
1176 @pytest.mark.parametrize(
1177 ("reason", "should_reset"),
1178 (
1179 (
1180 "KEY_VALUES_MISMATCH",
1181 True,
1182 ),
1183 (
1184 "Boom",
1185 False,
1186 ),
1187 ),
1188 )
1189 async def test_context_error_handling(
1190 cloud: Cloud,
1191 valid_acme_mock: MockAcme,
1192 aioclient_mock: AiohttpClientMocker,
1193 snitun_mock: MockSnitun,
1194 reason: str,
1195 should_reset: bool,
1196 caplog: pytest.LogCaptureFixture,
1197 snapshot: SnapshotAssertion,
1198 mock_timing: None,
1199 ) -> None:
1200 """Test that we reset if we hit an error reason that require resetting."""
1201 aioclient_mock.post(
1202 f"https://{cloud.api_server}/instance/register",
1203 json={
1204 "domain": "test.dui.nabu.casa",
1205 "email": "[email protected]",
1206 "server": "rest-remote.nabu.casa",
1207 },
1208 )
1209
1210 ssl_error = SSLError()
1211 ssl_error.reason = reason
1212
1213 # Patch _create_context to raise SSL error directly
1214 with patch.object(cloud.remote, "_create_context", side_effect=ssl_error):
1215 assert cloud.remote._certificate_status is None
1216 await cloud.remote.load_backend()
1217
1218 await asyncio.sleep(0.1)
1219 assert cloud.remote._acme.call_reset == should_reset
1220 assert cloud.remote._certificate_status is CertificateStatus.SSL_CONTEXT_ERROR
1221
1222 assert snapshot == extract_log_messages(caplog)
1223
1224 await cloud.remote.stop()
1225
1226
1227 async def test_certificate_status_dispatcher(cloud: Cloud) -> None:
1228 """Test certificate status dispatcher functionality."""
1229 # Test status update dispatching
1230 cloud.remote._update_certificate_status(CertificateStatus.LOADING)
1231
1232 # Check that dispatcher was called
1233 assert len(cloud.client.mock_dispatcher) == 1
1234 assert cloud.client.mock_dispatcher[0] == (
1235 DISPATCH_CERTIFICATE_STATUS,
1236 CertificateStatus.LOADING,
1237 )
1238
1239 # Test second status update
1240 cloud.remote._update_certificate_status(CertificateStatus.ERROR)
1241
1242 assert len(cloud.client.mock_dispatcher) == 2
1243 assert cloud.client.mock_dispatcher[1] == (
1244 DISPATCH_CERTIFICATE_STATUS,
1245 CertificateStatus.ERROR,
1246 )
1247
1248 # Test duplicate status update (should be ignored)
1249 cloud.remote._update_certificate_status(CertificateStatus.ERROR)
1250
1251 # Should still be 2 calls since status didn't change
1252 assert len(cloud.client.mock_dispatcher) == 2
1253
1254
1255 async def test_recreate_acme_calls_reset_when_acme_exists(cloud: Cloud) -> None:
1256 """Test that _recreate_acme calls reset_acme when _acme exists."""
1257 mock_acme = MockAcme()
1258 cloud.remote._acme = mock_acme
1259
1260 await cloud.remote._recreate_acme(["new.example.com"], "[email protected]")
1261
1262 assert mock_acme.call_reset is True
1263 assert cloud.remote._acme is not mock_acme
1264
1265
1266 async def test_recreate_acme_with_certificate_available(cloud: Cloud) -> None:
1267 """Test _recreate_acme behavior when certificate is available."""
1268 mock_acme = MockAcme()
1269 cloud.remote._acme = mock_acme
1270
1271 await cloud.remote._recreate_acme(["new.example.com"], "[email protected]")
1272
1273 assert mock_acme.call_reset is True
1274 assert cloud.remote._acme is not mock_acme
1275
1276
1277 async def test_recreate_acme_without_certificate_available(cloud: Cloud) -> None:
1278 """Test _recreate_acme behavior when certificate is not available."""
1279 mock_acme = MockAcme()
1280 mock_acme.common_name = None
1281 cloud.remote._acme = mock_acme
1282
1283 await cloud.remote._recreate_acme(["new.example.com"], "[email protected]")
1284
1285 assert mock_acme.call_reset is True
1286 assert cloud.remote._acme is not mock_acme
1287
1288
1289 async def test_recreate_acme_with_error_status(cloud: Cloud) -> None:
1290 """Test _recreate_acme behavior when certificate status is ERROR."""
1291 mock_acme = MockAcme()
1292 cloud.remote._acme = mock_acme
1293 cloud.remote._certificate_status = CertificateStatus.ERROR
1294
1295 await cloud.remote._recreate_acme(["new.example.com"], "[email protected]")
1296
1297 assert mock_acme.call_reset is True
1298 assert cloud.remote._acme is not mock_acme
1299
1300
1301 async def test_recreate_acme_when_no_acme_exists(cloud: Cloud) -> None:
1302 """Test _recreate_acme behavior when no ACME handler exists."""
1303 cloud.remote._acme = None
1304
1305 await cloud.remote._recreate_acme(["test.example.com"], "[email protected]")
1306
1307 assert cloud.remote._acme is not None
1308
1309
1310 async def test_recreate_acme_integration_during_load_backend(
1311 cloud: Cloud,
1312 valid_acme_mock: MockAcme,
1313 aioclient_mock: AiohttpClientMocker,
1314 ) -> None:
1315 """Test _recreate_acme integration during load_backend with domain changes."""
1316 aioclient_mock.post(
1317 f"https://{cloud.api_server}/instance/register",
1318 json={
1319 "domain": "test.dui.nabu.casa",
1320 "email": "[email protected]",
1321 "server": "rest-remote.nabu.casa",
1322 "alias": ["new-alias.com"],
1323 },
1324 )
1325 aioclient_mock.post(
1326 f"https://{cloud.api_server}/account/instance/resolve_dns_cname",
1327 json=[
1328 "test.dui.nabu.casa",
1329 "_acme-challenge.test.dui.nabu.casa",
1330 ],
1331 )
1332
1333 valid_acme_mock.common_name = "test.dui.nabu.casa"
1334 valid_acme_mock.alternative_names = ["test.dui.nabu.casa", "old-alias.com"]
1335
1336 await cloud.remote.load_backend()
1337 await asyncio.sleep(0.1)
1338
1339 assert valid_acme_mock.call_reset is True
1340
1341 expected_domains = ["test.dui.nabu.casa", "new-alias.com"]
1342 assert valid_acme_mock.init_args == (
1343 cloud,
1344 expected_domains,
1345 "[email protected]",
1346 )
1347
1348
1349 @pytest.mark.parametrize(
1350 ("exception_type", "exception_message"),
1351 [
1352 (gaierror, "DNS resolution failed"),
1353 (RequestException, "Connection timeout"),
1354 ],
1355 )
1356 async def test_certificate_network_error_handling(
1357 cloud: Cloud,
1358 aioclient_mock: AiohttpClientMocker,
1359 snitun_mock: MockSnitun,
1360 caplog: pytest.LogCaptureFixture,
1361 snapshot: SnapshotAssertion,
1362 exception_type: type[Exception],
1363 exception_message: str,
1364 ) -> None:
1365 """Test network errors are handled properly during certificate issuance."""
1366
1367 class _MockAcmeClient(client.ClientV2):
1368 def __init__(self) -> None:
1369 pass
1370
1371 def new_order(self, _: Any) -> None:
1372 raise exception_type(exception_message)
1373
1374 class _MockAcme(AcmeHandler):
1375 @property
1376 def certificate_available(self) -> bool:
1377 return False
1378
1379 @property
1380 def alternative_names(self) -> list[str]:
1381 return ["test.dui.nabu.casa"]
1382
1383 def _generate_csr(self) -> bytes:
1384 return b""
1385
1386 def _create_client(self) -> None:
1387 self._acme_client = _MockAcmeClient()
1388
1389 valid = utcnow() + timedelta(days=1)
1390
1391 aioclient_mock.post(
1392 f"https://{cloud.api_server}/instance/register",
1393 json={
1394 "domain": "test.dui.nabu.casa",
1395 "email": "[email protected]",
1396 "server": "rest-remote.nabu.casa",
1397 },
1398 )
1399 aioclient_mock.post(
1400 f"https://{cloud.api_server}/instance/snitun_token",
1401 json={
1402 "token": "test-token",
1403 "server": "rest-remote.nabu.casa",
1404 "valid": valid.timestamp(),
1405 "throttling": 400,
1406 },
1407 )
1408
1409 with patch(
1410 "hass_nabucasa.remote.AcmeHandler",
1411 return_value=_MockAcme(cloud, [], "[email protected]", Mock()),
1412 ):
1413 cloud.client.prop_remote_autostart = True
1414 await cloud.remote.start()
1415 await asyncio.sleep(0.1)
1416
1417 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1418 assert cloud.remote.certificate_status == CertificateStatus.INITIAL_CERT_ERROR
1419
1420 # Verify the log messages with snapshot
1421 assert snapshot == extract_log_messages(caplog)
1422
1423
1424 async def test_load_backend_with_ping_targets(
1425 cloud: Cloud,
1426 valid_acme_mock: MockAcme,
1427 aioclient_mock: AiohttpClientMocker,
1428 snitun_mock: MockSnitun,
1429 mock_timing: None,
1430 ) -> None:
1431 """Test load_backend fetches ping targets and sends results with register."""
1432 valid = utcnow() + timedelta(days=1)
1433
1434 aioclient_mock.clear_requests()
1435 aioclient_mock.get(
1436 f"https://{cloud.api_server}/instance/remote_ping_targets",
1437 json={
1438 "targets": [
1439 {"ip": "1.2.3.4", "location": "us-east"},
1440 {"ip": "5.6.7.8", "location": "eu-west"},
1441 ],
1442 "timeout": 3000,
1443 "count": 2,
1444 },
1445 )
1446 aioclient_mock.post(
1447 f"https://{cloud.api_server}/instance/register",
1448 json={
1449 "domain": "test.dui.nabu.casa",
1450 "email": "[email protected]",
1451 "server": "rest-remote.nabu.casa",
1452 },
1453 )
1454 aioclient_mock.post(
1455 f"https://{cloud.api_server}/instance/snitun_token",
1456 json={
1457 "token": "test-token",
1458 "server": "rest-remote.nabu.casa",
1459 "valid": valid.timestamp(),
1460 "throttling": 400,
1461 },
1462 )
1463
1464 with patch(
1465 "hass_nabucasa.remote.utils.async_check_latency",
1466 return_value=[
1467 {
1468 "address": "1.2.3.4",
1469 "is_alive": True,
1470 "avg_rtt": 10.5,
1471 "max_rtt": 15.0,
1472 "min_rtt": 8.0,
1473 "reachable": True,
1474 },
1475 {
1476 "address": "5.6.7.8",
1477 "is_alive": True,
1478 "avg_rtt": 20.3,
1479 "max_rtt": 25.0,
1480 "min_rtt": 18.0,
1481 "reachable": True,
1482 },
1483 ],
1484 ) as mock_latency:
1485 await cloud.remote.load_backend()
1486 await asyncio.sleep(0.1)
1487
1488 mock_latency.assert_called_once_with(
1489 ["1.2.3.4", "5.6.7.8"],
1490 count=2,
1491 ping_timeout=3,
1492 privileged=True,
1493 )
1494
1495 # Verify register was called with ping_result
1496 register_calls = [
1497 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
1498 ]
1499 assert len(register_calls) == 1
1500 assert register_calls[0][2] == {
1501 "ping_result": [
1502 {"ip": "1.2.3.4", "avg": 10.5, "max": 15.0, "min": 8.0, "reachable": True},
1503 {"ip": "5.6.7.8", "avg": 20.3, "max": 25.0, "min": 18.0, "reachable": True},
1504 ],
1505 }
1506
1507 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1508 await cloud.remote.stop()
1509 await asyncio.sleep(0.1)
1510
1511
1512 async def test_load_backend_with_ping_targets_unreachable(
1513 cloud: Cloud,
1514 valid_acme_mock: MockAcme,
1515 aioclient_mock: AiohttpClientMocker,
1516 snitun_mock: MockSnitun,
1517 mock_timing: None,
1518 ) -> None:
1519 """Test that avg is None when a ping target is not alive."""
1520 valid = utcnow() + timedelta(days=1)
1521
1522 aioclient_mock.clear_requests()
1523 aioclient_mock.get(
1524 f"https://{cloud.api_server}/instance/remote_ping_targets",
1525 json={
1526 "targets": [
1527 {"ip": "1.2.3.4", "location": "us-east"},
1528 {"ip": "5.6.7.8", "location": "eu-west"},
1529 ],
1530 "timeout": 3000,
1531 "count": 2,
1532 },
1533 )
1534 aioclient_mock.post(
1535 f"https://{cloud.api_server}/instance/register",
1536 json={
1537 "domain": "test.dui.nabu.casa",
1538 "email": "[email protected]",
1539 "server": "rest-remote.nabu.casa",
1540 },
1541 )
1542 aioclient_mock.post(
1543 f"https://{cloud.api_server}/instance/snitun_token",
1544 json={
1545 "token": "test-token",
1546 "server": "rest-remote.nabu.casa",
1547 "valid": valid.timestamp(),
1548 "throttling": 400,
1549 },
1550 )
1551
1552 with patch(
1553 "hass_nabucasa.remote.utils.async_check_latency",
1554 return_value=[
1555 {
1556 "address": "1.2.3.4",
1557 "is_alive": True,
1558 "avg_rtt": 10.5,
1559 "max_rtt": 15.0,
1560 "min_rtt": 8.0,
1561 "reachable": True,
1562 },
1563 {
1564 "address": "5.6.7.8",
1565 "is_alive": False,
1566 "avg_rtt": 0.0,
1567 "max_rtt": 0.0,
1568 "min_rtt": 0.0,
1569 "reachable": False,
1570 },
1571 ],
1572 ):
1573 await cloud.remote.load_backend()
1574 await asyncio.sleep(0.1)
1575
1576 assert cloud.remote.latency_by_location == {
1577 "us-east": {"avg": 10.5},
1578 "eu-west": {"avg": None},
1579 }
1580
1581 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1582 await cloud.remote.stop()
1583 await asyncio.sleep(0.1)
1584
1585
1586 async def test_load_backend_ping_targets_empty(
1587 cloud: Cloud,
1588 valid_acme_mock: MockAcme,
1589 aioclient_mock: AiohttpClientMocker,
1590 snitun_mock: MockSnitun,
1591 mock_timing: None,
1592 ) -> None:
1593 """Test load_backend skips ping when no targets returned."""
1594 valid = utcnow() + timedelta(days=1)
1595
1596 aioclient_mock.clear_requests()
1597 aioclient_mock.get(
1598 f"https://{cloud.api_server}/instance/remote_ping_targets",
1599 json={"targets": [], "timeout": 5000, "count": 1},
1600 )
1601 aioclient_mock.post(
1602 f"https://{cloud.api_server}/instance/register",
1603 json={
1604 "domain": "test.dui.nabu.casa",
1605 "email": "[email protected]",
1606 "server": "rest-remote.nabu.casa",
1607 },
1608 )
1609 aioclient_mock.post(
1610 f"https://{cloud.api_server}/instance/snitun_token",
1611 json={
1612 "token": "test-token",
1613 "server": "rest-remote.nabu.casa",
1614 "valid": valid.timestamp(),
1615 "throttling": 400,
1616 },
1617 )
1618
1619 with patch(
1620 "hass_nabucasa.remote.utils.async_check_latency",
1621 ) as mock_latency:
1622 await cloud.remote.load_backend()
1623 await asyncio.sleep(0.1)
1624
1625 mock_latency.assert_not_called()
1626
1627 # Verify register was called without ping_result (no jsondata)
1628 register_calls = [
1629 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
1630 ]
1631 assert len(register_calls) == 1
1632 assert register_calls[0][2] is None
1633
1634 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1635 await cloud.remote.stop()
1636 await asyncio.sleep(0.1)
1637
1638
1639 async def test_load_backend_ping_targets_api_error(
1640 cloud: Cloud,
1641 valid_acme_mock: MockAcme,
1642 aioclient_mock: AiohttpClientMocker,
1643 snitun_mock: MockSnitun,
1644 mock_timing: None,
1645 ) -> None:
1646 """Test load_backend still works when ping targets API fails."""
1647 valid = utcnow() + timedelta(days=1)
1648
1649 aioclient_mock.clear_requests()
1650 aioclient_mock.get(
1651 f"https://{cloud.api_server}/instance/remote_ping_targets",
1652 status=500,
1653 json={"message": "Internal Server Error"},
1654 )
1655 aioclient_mock.post(
1656 f"https://{cloud.api_server}/instance/register",
1657 json={
1658 "domain": "test.dui.nabu.casa",
1659 "email": "[email protected]",
1660 "server": "rest-remote.nabu.casa",
1661 },
1662 )
1663 aioclient_mock.post(
1664 f"https://{cloud.api_server}/instance/snitun_token",
1665 json={
1666 "token": "test-token",
1667 "server": "rest-remote.nabu.casa",
1668 "valid": valid.timestamp(),
1669 "throttling": 400,
1670 },
1671 )
1672
1673 await cloud.remote.load_backend()
1674 await asyncio.sleep(0.1)
1675
1676 # Register should still succeed without ping_result
1677 register_calls = [
1678 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
1679 ]
1680 assert len(register_calls) == 1
1681 assert register_calls[0][2] is None
1682
1683 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1684 await cloud.remote.stop()
1685 await asyncio.sleep(0.1)
1686
1687
1688 async def test_load_backend_ping_latency_check_fails(
1689 cloud: Cloud,
1690 valid_acme_mock: MockAcme,
1691 aioclient_mock: AiohttpClientMocker,
1692 snitun_mock: MockSnitun,
1693 mock_timing: None,
1694 ) -> None:
1695 """Test load_backend still works when latency check fails."""
1696 valid = utcnow() + timedelta(days=1)
1697
1698 aioclient_mock.clear_requests()
1699 aioclient_mock.get(
1700 f"https://{cloud.api_server}/instance/remote_ping_targets",
1701 json={
1702 "targets": [{"ip": "1.2.3.4", "location": "us-east"}],
1703 "timeout": 5000,
1704 "count": 1,
1705 },
1706 )
1707 aioclient_mock.post(
1708 f"https://{cloud.api_server}/instance/register",
1709 json={
1710 "domain": "test.dui.nabu.casa",
1711 "email": "[email protected]",
1712 "server": "rest-remote.nabu.casa",
1713 },
1714 )
1715 aioclient_mock.post(
1716 f"https://{cloud.api_server}/instance/snitun_token",
1717 json={
1718 "token": "test-token",
1719 "server": "rest-remote.nabu.casa",
1720 "valid": valid.timestamp(),
1721 "throttling": 400,
1722 },
1723 )
1724
1725 with patch(
1726 "hass_nabucasa.remote.utils.async_check_latency",
1727 side_effect=utils.CheckLatencyError("All hosts are unreachable"),
1728 ):
1729 await cloud.remote.load_backend()
1730 await asyncio.sleep(0.1)
1731
1732 # Register should still succeed without ping_result
1733 register_calls = [
1734 call for call in aioclient_mock.mock_calls if "register" in str(call[1])
1735 ]
1736 assert len(register_calls) == 1
1737 assert register_calls[0][2] is None
1738
1739 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1740 await cloud.remote.stop()
1741 await asyncio.sleep(0.1)
1742
1743
1744 async def test_load_backend_ping_privileged_passed(
1745 cloud: Cloud,
1746 valid_acme_mock: MockAcme,
1747 aioclient_mock: AiohttpClientMocker,
1748 snitun_mock: MockSnitun,
1749 mock_timing: None,
1750 ) -> None:
1751 """Test that privileged_ping is passed through to async_check_latency."""
1752 valid = utcnow() + timedelta(days=1)
1753
1754 cloud.privileged_ping = True
1755
1756 aioclient_mock.clear_requests()
1757 aioclient_mock.get(
1758 f"https://{cloud.api_server}/instance/remote_ping_targets",
1759 json={
1760 "targets": [{"ip": "1.2.3.4", "location": "us-east"}],
1761 "timeout": 5000,
1762 "count": 1,
1763 },
1764 )
1765 aioclient_mock.post(
1766 f"https://{cloud.api_server}/instance/register",
1767 json={
1768 "domain": "test.dui.nabu.casa",
1769 "email": "[email protected]",
1770 "server": "rest-remote.nabu.casa",
1771 },
1772 )
1773 aioclient_mock.post(
1774 f"https://{cloud.api_server}/instance/snitun_token",
1775 json={
1776 "token": "test-token",
1777 "server": "rest-remote.nabu.casa",
1778 "valid": valid.timestamp(),
1779 "throttling": 400,
1780 },
1781 )
1782
1783 with patch(
1784 "hass_nabucasa.remote.utils.async_check_latency",
1785 return_value=[
1786 {
1787 "address": "1.2.3.4",
1788 "is_alive": True,
1789 "avg_rtt": 15.0,
1790 "max_rtt": 20.0,
1791 "min_rtt": 10.0,
1792 },
1793 ],
1794 ) as mock_latency:
1795 await cloud.remote.load_backend()
1796 await asyncio.sleep(0.1)
1797
1798 mock_latency.assert_called_once_with(
1799 ["1.2.3.4"],
1800 count=1,
1801 ping_timeout=5,
1802 privileged=True,
1803 )
1804
1805 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1806 await cloud.remote.stop()
1807 await asyncio.sleep(0.1)
1808
1809
1810 async def test_load_backend_ping_unprivileged_passed(
1811 cloud: Cloud,
1812 valid_acme_mock: MockAcme,
1813 aioclient_mock: AiohttpClientMocker,
1814 snitun_mock: MockSnitun,
1815 mock_timing: None,
1816 ) -> None:
1817 """Test that privileged_ping=False is passed through to async_check_latency."""
1818 valid = utcnow() + timedelta(days=1)
1819
1820 cloud.privileged_ping = False
1821
1822 aioclient_mock.clear_requests()
1823 aioclient_mock.get(
1824 f"https://{cloud.api_server}/instance/remote_ping_targets",
1825 json={
1826 "targets": [{"ip": "1.2.3.4", "location": "us-east"}],
1827 "timeout": 5000,
1828 "count": 1,
1829 },
1830 )
1831 aioclient_mock.post(
1832 f"https://{cloud.api_server}/instance/register",
1833 json={
1834 "domain": "test.dui.nabu.casa",
1835 "email": "[email protected]",
1836 "server": "rest-remote.nabu.casa",
1837 },
1838 )
1839 aioclient_mock.post(
1840 f"https://{cloud.api_server}/instance/snitun_token",
1841 json={
1842 "token": "test-token",
1843 "server": "rest-remote.nabu.casa",
1844 "valid": valid.timestamp(),
1845 "throttling": 400,
1846 },
1847 )
1848
1849 with patch(
1850 "hass_nabucasa.remote.utils.async_check_latency",
1851 return_value=[
1852 {
1853 "address": "1.2.3.4",
1854 "is_alive": True,
1855 "avg_rtt": 15.0,
1856 "max_rtt": 20.0,
1857 "min_rtt": 10.0,
1858 },
1859 ],
1860 ) as mock_latency:
1861 await cloud.remote.load_backend()
1862 await asyncio.sleep(0.1)
1863
1864 mock_latency.assert_called_once_with(
1865 ["1.2.3.4"],
1866 count=1,
1867 ping_timeout=5,
1868 privileged=False,
1869 )
1870
1871 assert cloud.remote.snitun_server == "rest-remote.nabu.casa"
1872 await cloud.remote.stop()
1873 await asyncio.sleep(0.1)