Debian Codegraph @

tests/test_remote.py

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