forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_embedded_setup.py
More file actions
1761 lines (1438 loc) · 73.4 KB
/
Copy pathtest_embedded_setup.py
File metadata and controls
1761 lines (1438 loc) · 73.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Unit tests for the in-process server bring-up orchestration (issue #1527).
``embedded_setup`` is the glue between the server manager and the webhook ingress:
the background bring-up sequence, repair issues on failure (Home Assistant must
keep running), connect-URL surfacing, teardown, and credential revocation on
removal. The integration is always-on — the config entry existing means the
server runs — so there is no enable/disable gate here.
Home Assistant / aiohttp are stubbed via ``_embedded_stubs`` (which also puts
the component package on sys.path). The server manager and webhook
register/unregister functions are patched so these tests exercise only the
orchestration decisions.
"""
from __future__ import annotations
import asyncio
import sys
from types import ModuleType, SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from ._embedded_stubs import install
install()
import custom_components.ha_mcp_tools.embedded_setup as esetup # noqa: E402
# Captured before any test patches it so the connect-URL tests can restore the
# real implementation regardless of the module-level spy.
_REAL_SURFACE_CONNECT_URLS = esetup._surface_connect_urls
from custom_components.ha_mcp_tools.const import ( # noqa: E402
DATA_BRINGUP_TASK,
DATA_MANAGER,
DATA_PENDING_UPDATE_NOTIFY,
DATA_SECRET_PATH,
DATA_UPDATE_COORDINATOR,
DATA_WEBHOOK_ID,
DEFAULT_PIP_SPEC,
DIST_NAME_DEV,
DIST_NAME_STABLE,
DOMAIN,
ISSUE_COMPONENT_OUTDATED,
ISSUE_PACKAGE_FAILED,
ISSUE_START_FAILED,
ISSUE_UPDATE_HELD,
OPT_AUTO_UPDATE,
OPT_PIP_SPEC,
OPT_WEBHOOK_AUTH,
UPDATE_HOLD_DOCS_URL,
WEBHOOK_AUTH_HA,
)
from custom_components.ha_mcp_tools.coordinator import ServerVersionInfo # noqa: E402
def _make_hass() -> MagicMock:
hass = MagicMock(name="hass")
hass.data = {}
hass.config.skip_pip = False
def _update_entry(entry, *, data=None, **_kw):
if data is not None:
entry.data = data
hass.config_entries.async_update_entry = MagicMock(side_effect=_update_entry)
def _create_task(coro, *args, **kwargs):
# The update-check paths schedule the HACS nudge fire-and-forget; these
# tests assert the scheduling decision, not the nudge's own behavior
# (covered in test_hacs_nudge) — close the real coroutine so it is never
# left un-awaited.
if asyncio.iscoroutine(coro):
coro.close()
hass.async_create_task = MagicMock(side_effect=_create_task)
async def _executor(func, *args):
return func(*args)
# The bring-up path runs the component-compat check, which offloads the
# MIN_COMPONENT_VERSION read to the executor; give every hass a working one
# (the real check then self-skips because ha_mcp is not installed here).
hass.async_add_executor_job = AsyncMock(side_effect=_executor)
return hass
def _make_entry(*, options=None, data=None) -> MagicMock:
entry = MagicMock(name="entry")
entry.options = {} if options is None else dict(options)
entry.data = {DATA_SECRET_PATH: "/private_x"} if data is None else dict(data)
return entry
@pytest.fixture
def fake_manager(monkeypatch):
"""Patch EmbeddedServerManager with a real fake class.
A real class (not a lambda/MagicMock) is required because
``async_teardown_server`` does ``isinstance(manager, EmbeddedServerManager)``.
The async methods live on the class as shared AsyncMocks so tests assert on
``fake_manager.async_start`` regardless of which instance the code built.
Returns the class.
"""
class FakeManager:
port = 9584
async_start = AsyncMock()
async_stop = AsyncMock()
async_revoke_credentials = AsyncMock()
def __init__(self, hass, entry):
self.hass = hass
self.entry = entry
monkeypatch.setattr(esetup, "EmbeddedServerManager", FakeManager)
return FakeManager
@pytest.fixture(autouse=True)
def _spy(monkeypatch):
"""Patch webhook register/unregister, issue-registry, and connect-URL
surfacing to spies (the connect-URL tests restore the real surfacing)."""
monkeypatch.setattr(esetup, "async_register_webhook", AsyncMock(return_value=False))
monkeypatch.setattr(esetup, "async_unregister_webhook", AsyncMock())
monkeypatch.setattr(esetup, "async_register_llm_api", AsyncMock())
monkeypatch.setattr(esetup, "async_unregister_llm_api", MagicMock())
monkeypatch.setattr(esetup.ir, "async_create_issue", MagicMock())
monkeypatch.setattr(esetup.ir, "async_delete_issue", MagicMock())
monkeypatch.setattr(esetup, "_surface_connect_urls", MagicMock())
class TestBringUp:
async def test_legacy_bring_up_passes_creds_active_verdict(
self, fake_manager, monkeypatch
):
# The bring-up must consult legacy_credentials_active and hand its
# verdict to _surface_connect_urls -- the gate that keeps rotated
# credentials out of the startup log (review finding on #1880).
monkeypatch.setattr(
esetup, "legacy_credentials_active", MagicMock(return_value=False)
)
hass = _make_hass()
entry = _make_entry(
options={esetup.OPT_WEBHOOK_AUTH: esetup.WEBHOOK_AUTH_LEGACY}
)
await esetup.async_bring_up_server(hass, entry)
esetup.legacy_credentials_active.assert_called_once()
assert (
esetup._surface_connect_urls.call_args.kwargs["oauth_creds_active"] is False
)
async def test_legacy_restart_needed_files_repair(self, fake_manager, monkeypatch):
# Review gap: every bring-up test mocked async_register_webhook with
# restart_needed=False, so the create-issue branch of
# _async_update_legacy_oauth_issue was never exercised.
monkeypatch.setattr(
esetup, "async_register_webhook", AsyncMock(return_value=True)
)
hass = _make_hass()
entry = _make_entry(
options={esetup.OPT_WEBHOOK_AUTH: esetup.WEBHOOK_AUTH_LEGACY}
)
await esetup.async_bring_up_server(hass, entry)
created = [
c
for c in esetup.ir.async_create_issue.call_args_list
if esetup.ISSUE_LEGACY_OAUTH_RESTART in c.args
]
assert created, "legacy-OAuth restart repair was not filed"
assert created[0].kwargs["is_fixable"] is True
cleared = {c.args[2] for c in esetup.ir.async_delete_issue.call_args_list}
assert esetup.ISSUE_LEGACY_OAUTH_RESTART not in cleared
# The same restart-needed verdict must thread into the connect-URL
# surfacing so the log carries the first-enable "not live" caveat --
# deleting that kwarg would silently drop the caveat.
assert (
esetup._surface_connect_urls.call_args.kwargs["oauth_restart_pending"]
is True
)
async def test_success_starts_registers_and_surfaces(
self, fake_manager, monkeypatch
):
# The enumerated adapter hosts must be forwarded into the connect-URL
# surfacing, or the startup log (the feature's primary surface) silently
# loses the per-interface URLs while every other test stays green
# (#1862). Mirrors the config-flow forwarding assertion.
monkeypatch.setattr(
esetup, "async_get_lan_hosts", AsyncMock(return_value=["10.0.1.3"])
)
hass = _make_hass()
entry = _make_entry()
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_start.assert_awaited_once()
esetup.async_register_webhook.assert_awaited_once()
esetup._surface_connect_urls.assert_called_once()
assert esetup._surface_connect_urls.call_args.kwargs["extra_hosts"] == [
"10.0.1.3"
]
assert isinstance(hass.data[DOMAIN][DATA_MANAGER], fake_manager)
esetup.ir.async_create_issue.assert_not_called()
# Conversation-agent LLM API (#1745): registered with the running
# server's port + secret path.
kwargs = esetup.async_register_llm_api.await_args.kwargs
assert kwargs["port"] == 9584
assert kwargs["secret_path"] == "/private_x"
async def test_success_clears_stale_repair_issues(self, fake_manager):
# Review gap: a successful bring-up must clear EVERY repair-issue id
# left by a previous failed attempt, or a fixed install keeps showing
# a stale repair forever. The update-held issue clears here too: a
# reload that reached bring-up either bypassed the hold deliberately
# (Install button) or made it moot, and the post-setup coordinator
# refresh re-files it if it still applies.
hass = _make_hass()
entry = _make_entry()
await esetup.async_bring_up_server(hass, entry)
cleared = {c.args[2] for c in esetup.ir.async_delete_issue.call_args_list}
assert cleared == {
esetup.ISSUE_PACKAGE_FAILED,
esetup.ISSUE_START_FAILED,
esetup.ISSUE_UPDATE_HELD,
# A non-legacy bring-up (async_register_webhook returned
# restart_needed=False) also clears any stale legacy-OAuth restart
# repair from a prior legacy configuration.
esetup.ISSUE_LEGACY_OAUTH_RESTART,
}
async def test_local_only_skips_endpoint_but_keeps_forwarding(
self, fake_manager, caplog
):
# Owner request: enable_webhook=False must never register the webhook
# endpoint (Nabu Casa path dead) while the server still starts; the log
# carries the local-only note. The forwarding config must still be set
# up (register_endpoint=False) or the sidebar settings panel 503s
# forever (#1803).
import logging
hass = _make_hass()
entry = _make_entry(options={esetup.OPT_ENABLE_WEBHOOK: False})
with caplog.at_level(logging.INFO):
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_start.assert_awaited_once()
esetup.async_register_webhook.assert_awaited_once()
kwargs = esetup.async_register_webhook.await_args.kwargs
assert kwargs["register_endpoint"] is False
esetup._surface_connect_urls.assert_called_once()
assert "local-only" in caplog.text
async def test_passes_auth_mode_port_and_secret_to_webhook(self, fake_manager):
hass = _make_hass()
entry = _make_entry(
options={OPT_WEBHOOK_AUTH: WEBHOOK_AUTH_HA},
data={DATA_SECRET_PATH: "/private_secret"},
)
await esetup.async_bring_up_server(hass, entry)
kwargs = esetup.async_register_webhook.await_args.kwargs
assert kwargs["auth_mode"] == WEBHOOK_AUTH_HA
assert kwargs["port"] == 9584
assert kwargs["secret_path"] == "/private_secret"
assert kwargs["register_endpoint"] is True
async def test_llm_api_option_off_skips_registration(self, fake_manager, caplog):
# The Conversation-agent LLM API toggle (#1745, default on): turning
# it off must skip the registration while the server itself, the
# webhook, and the rest of the bring-up run unchanged.
import logging
hass = _make_hass()
entry = _make_entry(options={esetup.OPT_ENABLE_LLM_API: False})
with caplog.at_level(logging.INFO):
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_start.assert_awaited_once()
esetup.async_register_webhook.assert_awaited_once()
esetup.async_register_llm_api.assert_not_awaited()
assert "LLM API disabled by option" in caplog.text
async def test_package_failure_files_package_issue_and_skips_webhook(
self, fake_manager
):
hass = _make_hass()
entry = _make_entry()
fake_manager.async_start.side_effect = esetup.EmbeddedServerError(
"pip failed", kind="package"
)
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_stop.assert_awaited_once() # teardown ran
assert DATA_MANAGER not in hass.data.get(DOMAIN, {})
esetup.async_register_webhook.assert_not_awaited()
esetup.async_register_llm_api.assert_not_awaited()
# The failure kind selects the package-install repair issue.
assert esetup.ir.async_create_issue.call_args.args[2] == ISSUE_PACKAGE_FAILED
async def test_start_failure_files_start_issue(self, fake_manager):
hass = _make_hass()
entry = _make_entry()
fake_manager.async_start.side_effect = esetup.EmbeddedServerError(
"bind failed", kind="start"
)
await esetup.async_bring_up_server(hass, entry)
assert esetup.ir.async_create_issue.call_args.args[2] == ISSUE_START_FAILED
async def test_unexpected_error_files_start_issue(self, fake_manager):
hass = _make_hass()
entry = _make_entry()
# Server started, but webhook registration raised a non-EmbeddedServerError.
esetup.async_register_webhook.side_effect = RuntimeError("register boom")
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_stop.assert_awaited_once()
assert esetup.ir.async_create_issue.call_args.args[2] == ISSUE_START_FAILED
async def test_cancelled_tears_down_and_reraises(self, fake_manager):
hass = _make_hass()
entry = _make_entry()
fake_manager.async_start.side_effect = asyncio.CancelledError
with pytest.raises(asyncio.CancelledError):
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_stop.assert_awaited_once() # partial state torn down
esetup.ir.async_create_issue.assert_not_called() # cancellation isn't a fault
async def test_package_failure_drops_pending_update_marker(self, fake_manager):
# The install did not land: the deferred "updated" notification must
# never fire for it - the repair issue is the user-facing signal.
hass = _make_hass()
hass.data[DOMAIN] = {DATA_PENDING_UPDATE_NOTIFY: {"old": "7.9.0"}}
entry = _make_entry()
fake_manager.async_start.side_effect = esetup.EmbeddedServerError(
"pip failed", kind="package"
)
await esetup.async_bring_up_server(hass, entry)
assert DATA_PENDING_UPDATE_NOTIFY not in hass.data[DOMAIN]
async def test_cancelled_bringup_keeps_pending_update_marker(self, fake_manager):
# Deliberately NOT dropped on cancellation: this bring-up never ran (the
# entry was unloaded before it started), so the marker belongs to
# whichever bring-up runs next, not to this cancelled attempt.
hass = _make_hass()
hass.data[DOMAIN] = {DATA_PENDING_UPDATE_NOTIFY: {"old": "7.9.0"}}
entry = _make_entry()
fake_manager.async_start.side_effect = asyncio.CancelledError
with pytest.raises(asyncio.CancelledError):
await esetup.async_bring_up_server(hass, entry)
assert hass.data[DOMAIN][DATA_PENDING_UPDATE_NOTIFY] == {"old": "7.9.0"}
class TestTeardown:
async def test_unregisters_and_stops_without_revoking(self, fake_manager):
hass = _make_hass()
entry = _make_entry()
await esetup.async_bring_up_server(hass, entry)
fake_manager.async_stop.reset_mock()
await esetup.async_teardown_server(hass)
esetup.async_unregister_webhook.assert_awaited()
esetup.async_unregister_llm_api.assert_called()
fake_manager.async_stop.assert_awaited_once()
assert DATA_MANAGER not in hass.data.get(DOMAIN, {})
# A reload must keep the provisioned token.
fake_manager.async_revoke_credentials.assert_not_awaited()
async def test_teardown_is_noop_when_not_running(self, fake_manager):
hass = _make_hass()
await esetup.async_teardown_server(hass) # must not raise
esetup.async_unregister_webhook.assert_awaited_once()
class TestRevokeOnRemove:
async def test_revokes_credentials_and_clears_issues(self, fake_manager):
hass = _make_hass()
entry = _make_entry()
await esetup.async_revoke_credentials_on_remove(hass, entry)
fake_manager.async_revoke_credentials.assert_awaited_once()
esetup.ir.async_delete_issue.assert_called()
async def test_clears_legacy_oauth_restart_repair(self, fake_manager):
# The legacy-OAuth restart repair is filed only from bring-up, which
# never runs again for a removed entry — so removal must clear it too,
# or a still-pending restart leaves a dangling warning for a gone server.
hass = _make_hass()
entry = _make_entry()
await esetup.async_revoke_credentials_on_remove(hass, entry)
cleared = {c.args[2] for c in esetup.ir.async_delete_issue.call_args_list}
assert esetup.ISSUE_LEGACY_OAUTH_RESTART in cleared
# ---------------------------------------------------------------------------
# Connect-URL surfacing (network + cloud lazily imported)
# ---------------------------------------------------------------------------
def _install_network_cloud(*, cloud_url=None, local_url=None):
"""Install fake homeassistant.helpers.network + components.cloud modules.
``cloud_url``/``local_url`` None ⇒ the corresponding lookup raises its
"unavailable" exception (the branch the code guards for).
"""
class NoURLAvailableError(Exception):
pass
class CloudNotAvailable(Exception):
pass
net = ModuleType("homeassistant.helpers.network")
net.NoURLAvailableError = NoURLAvailableError
def get_url(hass, *, allow_external=False, prefer_external=False):
if local_url is None:
raise NoURLAvailableError
return local_url
net.get_url = get_url
cloud = ModuleType("homeassistant.components.cloud")
cloud.CloudNotAvailable = CloudNotAvailable
def async_remote_ui_url(hass):
if cloud_url is None:
raise CloudNotAvailable
return cloud_url
cloud.async_remote_ui_url = async_remote_ui_url
sys.modules["homeassistant.helpers.network"] = net
sys.modules["homeassistant.components.cloud"] = cloud
def _install_adapters(adapters=None, *, error=None):
"""Install a fake ``homeassistant.components.network.async_get_adapters``.
``error`` set ⇒ the lookup raises it (the degrade-to-empty branch). The
parent-package attribute is set too: ``homeassistant.components`` is a
MagicMock here, so ``from homeassistant.components import network`` reads the
child attribute rather than the ``sys.modules`` entry alone.
"""
net = ModuleType("homeassistant.components.network")
async def async_get_adapters(hass):
if error is not None:
raise error
return adapters or []
net.async_get_adapters = async_get_adapters
sys.modules["homeassistant.components.network"] = net
sys.modules["homeassistant.components"].network = net
return net
class TestSurfaceConnectUrls:
@pytest.fixture(autouse=True)
def _restore_surface(self, monkeypatch, _spy):
# Depend on the module spy so this runs AFTER it, then restore the REAL
# _surface_connect_urls and spy only the persistent-notification call.
monkeypatch.setattr(esetup, "_surface_connect_urls", _REAL_SURFACE_CONNECT_URLS)
self.notif = MagicMock()
monkeypatch.setattr(esetup.persistent_notification, "async_create", self.notif)
yield
def _message(self) -> str:
return (
self.notif.call_args.kwargs.get("message") or self.notif.call_args.args[1]
)
def test_notification_carries_no_secrets_urls_go_to_log(self, caplog):
# Review finding (Patch76): persistent notifications are visible to
# every authenticated user, so the message must carry NO connect URL
# or secret path - those go to the admin-only log; the notification
# points at the admin-only surfaces.
import logging
_install_network_cloud(
cloud_url="https://abc.ui.nabu.casa", local_url="http://192.168.1.5:8123"
)
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
self.notif.assert_called_once()
message = self._message()
assert "mcp_id" not in message
assert "/p " not in message
assert "[HA-MCP settings panel](/ha-mcp)" in message
assert "Configure" in message
assert "https://abc.ui.nabu.casa/api/webhook/mcp_id" in caplog.text
assert "http://192.168.1.5:8123/api/webhook/mcp_id" in caplog.text
def test_notification_excludes_multi_interface_urls(self, caplog):
# #1862: the per-interface expansion multiplies the secret-bearing
# direct-access lines; none of the extra hosts (or the secret path) may
# leak into the all-users persistent notification - they belong to the
# admin-only log only.
import logging
_install_network_cloud(cloud_url=None, local_url="http://10.0.2.3:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(
hass, entry, "none", extra_hosts=["10.0.2.3", "10.0.1.3"]
)
message = self._message()
assert "10.0.1.3" not in message
assert "10.0.2.3" not in message
assert "/private_x" not in message
# Both interfaces' URLs DID reach the admin-only log.
assert "http://10.0.2.3:8123/api/webhook/mcp_id" in caplog.text
assert "http://10.0.1.3:8123/api/webhook/mcp_id" in caplog.text
assert "http://10.0.1.3:9584/private_x" in caplog.text
def test_external_url_option_leads_the_list(self, caplog):
# Owner request (webhook-proxy app parity): a configured external URL
# is shown FIRST, ahead of Nabu Casa and the local address.
_install_network_cloud(
cloud_url="https://abc.ui.nabu.casa", local_url="http://192.168.1.5:8123"
)
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"},
options={esetup.OPT_EXTERNAL_URL: "https://ha.example.com/"},
)
import logging
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
first = next(
line for line in caplog.text.splitlines() if "/api/webhook/" in line
)
assert "https://ha.example.com/api/webhook/mcp_id" in first
assert "https://abc.ui.nabu.casa/api/webhook/mcp_id" in caplog.text
# The rename commit's discoverability contract: the running
# notification links the sidebar settings panel and carries the
# HA-MCP Server title (the only path from "it is running" to the UI).
assert "[HA-MCP settings panel](/ha-mcp)" in self._message()
assert self.notif.call_args.kwargs.get("title") == "HA-MCP Server"
def test_falls_back_to_relative_url_when_none_available(self, caplog):
import logging
_install_network_cloud(cloud_url=None, local_url=None)
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "ha_auth")
self.notif.assert_called_once()
assert "/api/webhook/mcp_id" in caplog.text
assert "mcp_id" not in self._message()
def test_lan_bind_logs_direct_access_with_configured_port(self, caplog):
# Explicit 0.0.0.0 + custom port: the direct URL (with that port)
# appears in the admin-only log.
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_BIND_HOST: "0.0.0.0", esetup.OPT_SERVER_PORT: 9999},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
# Strengthened: the direct line names the resolved host, not just the port.
assert "http://192.168.1.5:9999/priv (direct access)" in caplog.text
def test_default_bind_logs_direct_access_line(self, caplog):
# LAN default (add-on parity): no explicit bind option -> the direct
# URL is part of the admin-only LOG output (never the notification).
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
# Strengthened: the resolved host rides the default-port direct line.
assert "http://192.168.1.5:9584/priv (direct access)" in caplog.text
assert "/priv" not in self._message()
def test_loopback_bind_omits_direct_access_line(self, caplog):
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_BIND_HOST: "127.0.0.1"},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
assert "(direct access)" not in caplog.text
def test_local_only_surface_has_no_webhook_urls(self, caplog):
import logging
_install_network_cloud(
cloud_url="https://abc.ui.nabu.casa", local_url="http://192.168.1.5:8123"
)
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_EXTERNAL_URL: "https://ha.example.com"},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none", webhook_enabled=False)
assert "/api/webhook/" not in caplog.text
# Strengthened: even in local-only mode the direct line names the host.
assert "http://192.168.1.5:9584/priv (direct access)" in caplog.text
assert "disabled" in self._message()
def test_legacy_active_creds_go_to_log_never_notification(self, caplog):
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(
hass,
entry,
esetup.WEBHOOK_AUTH_LEGACY,
oauth_client_id="cid-abc123",
oauth_client_secret="sec-xyz789",
)
assert "cid-abc123" in caplog.text
assert "sec-xyz789" in caplog.text
assert "cid-abc123" not in self._message()
assert "sec-xyz789" not in self._message()
# Live views (no pending restart): no not-live caveat.
assert "not live until the restart" not in caplog.text
def test_legacy_first_enable_logs_creds_with_not_live_caveat(self, caplog):
# Review finding on #1880: first-enable mid-session late-binds the
# views, so the credentials ARE the bound identity (logged in full)
# but /authorize is not live until the restart the repair asks for --
# the log must say so, matching the options hint and regenerate text.
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(
hass,
entry,
esetup.WEBHOOK_AUTH_LEGACY,
oauth_client_id="cid-abc123",
oauth_client_secret="sec-xyz789",
oauth_creds_active=True,
oauth_restart_pending=True,
)
# Credentials still shown (they are the ones that will be served)...
assert "cid-abc123" in caplog.text
assert "sec-xyz789" in caplog.text
# ...with the not-live-until-restart caveat.
assert "not live until the restart" in caplog.text
def test_legacy_pending_rotation_withholds_creds_from_log(self, caplog):
# Review finding on #1880: while a rotation is pending the restart,
# the bound views still serve the OLD identity, so an outstanding
# token stays valid and can read this log through the server's own
# log tools. The NEW credentials must not appear anywhere in it.
import logging
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(
hass,
entry,
esetup.WEBHOOK_AUTH_LEGACY,
oauth_client_id="cid-abc123",
oauth_client_secret="sec-xyz789",
oauth_creds_active=False,
)
assert "cid-abc123" not in caplog.text
assert "sec-xyz789" not in caplog.text
assert "cid-abc123" not in self._message()
assert "sec-xyz789" not in self._message()
# The log still tells the admin where the new credentials live.
assert "Configure" in caplog.text
def test_cloud_import_error_falls_back_to_local_url(self, monkeypatch, caplog):
# Review gap: plain HA Core has no cloud integration at all - the
# ImportError branch must degrade to the local URL, not raise.
import builtins
real_import = builtins.__import__
def _no_cloud(name, *a, **k):
if name.startswith("homeassistant.components.cloud"):
raise ImportError(name)
return real_import(name, *a, **k)
monkeypatch.setattr(builtins, "__import__", _no_cloud)
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/p"})
import logging
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
assert "http://192.168.1.5:8123/api/webhook/mcp_id" in caplog.text
def test_default_options_create_notification_with_panel_line(
self, monkeypatch, caplog
):
# Baseline for the two UX toggles: with neither option stored, the
# start-up notification is created (async_create) and its message links
# the sidebar settings panel; nothing is dismissed.
import logging
dismiss = MagicMock()
monkeypatch.setattr(esetup.persistent_notification, "async_dismiss", dismiss)
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"})
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
self.notif.assert_called_once()
assert "[HA-MCP settings panel](/ha-mcp)" in self._message()
dismiss.assert_not_called()
def test_startup_notification_ends_with_disable_instructions(self):
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"})
esetup._surface_connect_urls(hass, entry, "none")
assert self._message().endswith(
"\n\n"
"To disable this notification, uncheck the startup notification box "
"on that same configuration screen.\n"
)
def test_startup_notification_off_dismisses_and_skips_create(
self, monkeypatch, caplog
):
# enable_startup_notification=False: no persistent notification is
# created; instead any stale one is dismissed by its id. The connect
# URLs still reach the admin-only INFO log unchanged.
import logging
dismiss = MagicMock()
monkeypatch.setattr(esetup.persistent_notification, "async_dismiss", dismiss)
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_ENABLE_STARTUP_NOTIFICATION: False},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
# No notification created.
self.notif.assert_not_called()
# The stale one is dismissed by the connect notification's id.
dismiss.assert_called_once()
dismissed_id = dismiss.call_args.kwargs.get("notification_id") or (
dismiss.call_args.args[1] if len(dismiss.call_args.args) > 1 else None
)
assert dismissed_id == esetup._NOTIFICATION_ID == "ha_mcp_tools_server_connect"
assert dismiss.call_args.args[0] is hass
# The INFO connect-URL log still happens.
assert "HA-MCP in-process server is running" in caplog.text
assert "http://192.168.1.5:8123/api/webhook/mcp_id" in caplog.text
def test_sidebar_panel_off_omits_panel_line_from_notification(
self, monkeypatch, caplog
):
# enable_sidebar_panel=False (start-up notification still on): the
# notification is created, but its message drops the sidebar panel line
# (there is no panel to link to). The rest of the notification stays.
import logging
dismiss = MagicMock()
monkeypatch.setattr(esetup.persistent_notification, "async_dismiss", dismiss)
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_ENABLE_SIDEBAR_PANEL: False},
)
with caplog.at_level(logging.INFO):
esetup._surface_connect_urls(hass, entry, "none")
self.notif.assert_called_once()
dismiss.assert_not_called()
message = self._message()
assert "[HA-MCP settings panel](/ha-mcp)" not in message
assert "(/ha-mcp)" not in message
# Still a real notification: the admin-only Configure pointer remains.
assert "Configure" in message
assert self.notif.call_args.kwargs.get("title") == "HA-MCP Server"
class TestBuildConnectUrls:
"""Direct coverage of ``build_connect_urls`` — the shared URL resolver that
``_surface_connect_urls`` (log/notification) and the config flow's Configure
hint both call. Exercised here without the surfacing layer so the resolution
decisions (host, secret-path guard, webhook-disabled) are asserted directly.
"""
def test_direct_access_line_carries_resolved_host(self):
# 0.0.0.0 bind: the direct-access URL must name the ACTUAL resolved host
# (from get_url), not a placeholder, so an admin can paste it verbatim.
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(hass, entry)
direct = [u for u in urls if "(direct access)" in u]
assert direct == ["http://192.168.1.5:9584/private_x (direct access)"]
def test_missing_secret_path_omits_direct_access_line(self):
# Guard added in this PR: a URL must never render without its secret
# segment, so a missing secret path drops the direct-access line entirely
# rather than emitting a credential-less (and therefore useless) URL.
_install_network_cloud(cloud_url=None, local_url="http://192.168.1.5:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id"}, # no DATA_SECRET_PATH
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(hass, entry)
assert not any("(direct access)" in u for u in urls)
def test_webhook_disabled_returns_no_webhook_urls(self):
# Local-only mode: the webhook is never registered, so no /api/webhook/
# URL may be surfaced — the external, Nabu Casa, and local webhook forms
# are all suppressed even though every source is otherwise available.
_install_network_cloud(
cloud_url="https://abc.ui.nabu.casa", local_url="http://192.168.1.5:8123"
)
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_EXTERNAL_URL: "https://ha.example.com"},
)
urls = esetup.build_connect_urls(hass, entry, webhook_enabled=False)
assert not any("/api/webhook/" in u for u in urls)
def test_multiple_interfaces_expand_both_lines(self):
# #1862: a multi-interface / multi-VLAN host surfaces one webhook and one
# direct-access URL per enabled LAN address, canonical get_url host first.
_install_network_cloud(cloud_url=None, local_url="http://10.0.2.3:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(
hass, entry, extra_hosts=["10.0.2.3", "10.0.1.3"]
)
webhook = [u for u in urls if "/api/webhook/" in u]
direct = [u for u in urls if "(direct access)" in u]
assert webhook == [
"http://10.0.2.3:8123/api/webhook/mcp_id",
"http://10.0.1.3:8123/api/webhook/mcp_id",
]
assert direct == [
"http://10.0.2.3:9584/private_x (direct access)",
"http://10.0.1.3:9584/private_x (direct access)",
]
def test_extra_hosts_deduped_against_get_url_host(self):
# The get_url host repeated in the adapter list must not double-list.
_install_network_cloud(cloud_url=None, local_url="http://10.0.2.3:8123")
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(hass, entry, extra_hosts=["10.0.2.3"])
assert sum("(direct access)" in u for u in urls) == 1
assert sum("/api/webhook/" in u for u in urls) == 1
def test_extra_hosts_surface_direct_line_without_get_url(self):
# get_url unavailable but adapters known: the direct-access line still
# lists the real adapter hosts rather than only a placeholder.
_install_network_cloud(cloud_url=None, local_url=None)
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/private_x"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(hass, entry, extra_hosts=["10.0.1.3"])
direct = [u for u in urls if "(direct access)" in u]
assert direct == ["http://10.0.1.3:9584/private_x (direct access)"]
def test_portless_internal_url_swaps_host_without_a_port(self):
# A reverse-proxied internal URL has no port; _swap_url_host must keep it
# port-less for the extra adapter host rather than inventing one.
_install_network_cloud(cloud_url=None, local_url="https://ha.internal")
hass = _make_hass()
entry = _make_entry(data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"})
urls = esetup.build_connect_urls(hass, entry, extra_hosts=["10.0.1.3"])
webhook = [u for u in urls if "/api/webhook/" in u]
assert webhook == [
"https://ha.internal/api/webhook/mcp_id",
"https://10.0.1.3/api/webhook/mcp_id",
]
def test_direct_line_uses_placeholder_when_no_host_resolves(self):
# bind-all + secret present but no get_url host and no adapters: the
# direct line falls back to the <home-assistant-ip> placeholder rather
# than dropping the line or rendering a host-less URL.
_install_network_cloud(cloud_url=None, local_url=None)
hass = _make_hass()
entry = _make_entry(
data={DATA_WEBHOOK_ID: "mcp_id", DATA_SECRET_PATH: "/priv"},
options={esetup.OPT_BIND_HOST: esetup.BIND_HOST_ALL},
)
urls = esetup.build_connect_urls(hass, entry)
direct = [u for u in urls if "(direct access)" in u]
assert direct == ["http://<home-assistant-ip>:9584/priv (direct access)"]
class TestAsyncGetLanHosts:
"""Coverage of ``async_get_lan_hosts`` — the per-interface IPv4 enumeration
that feeds ``build_connect_urls`` ``extra_hosts`` (#1862)."""
async def test_lists_enabled_adapter_ipv4_in_order(self):
_install_adapters(
[
{"enabled": True, "ipv4": [{"address": "10.0.2.3"}]},
{
"enabled": True,
"ipv4": [{"address": "10.0.1.3"}, {"address": "10.0.1.4"}],
},
{"enabled": False, "ipv4": [{"address": "10.9.9.9"}]},
]
)
hosts = await esetup.async_get_lan_hosts(_make_hass())
# Disabled adapter dropped; enabled addresses kept in adapter order.
assert hosts == ["10.0.2.3", "10.0.1.3", "10.0.1.4"]
async def test_degrades_to_empty_on_error(self):
# A lookup failure must yield [] so URL surfacing (and bring-up) never
# breaks for a display-only enumeration.
_install_adapters(error=RuntimeError("no network component"))
hosts = await esetup.async_get_lan_hosts(_make_hass())
assert hosts == []
async def test_degrades_to_empty_on_malformed_adapter(self):
# A malformed adapter entry (missing keys) must also degrade to [] rather
# than escaping the loop into async_bring_up_server's handler, which would
# tear the running server down for a display-only lookup.
_install_adapters([{"enabled": True}]) # no "ipv4" key
hosts = await esetup.async_get_lan_hosts(_make_hass())
assert hosts == []
# ---------------------------------------------------------------------------
# Automatic-update decision (given a ServerVersionInfo from the coordinator)
# ---------------------------------------------------------------------------
def _make_async_hass() -> MagicMock:
"""A hass with an inline executor (from ``_make_hass``) and awaitable reload."""
hass = _make_hass()
hass.config_entries.async_reload = AsyncMock()
return hass
class _FakeTask:
"""Stand-in for the bring-up ``asyncio.Task`` — only ``.done()`` is read."""
def __init__(self, *, done: bool) -> None:
self._done = done