forked from homeassistant-ai/ha-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_tools_addons.py
More file actions
6576 lines (5770 loc) · 248 KB
/
Copy pathtest_tools_addons.py
File metadata and controls
6576 lines (5770 loc) · 248 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 add-on tools (AddOnTools, manage_addon, _validate_addon_access, _call_addon_api, _call_addon_ws, list_addons)."""
import json
import ssl
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
import pytest
from fastmcp.exceptions import ToolError
# The vendored classes — the same ones tools_addons raises/catches; the
# shared site-packages websockets is a DIFFERENT set of classes that
# except/isinstance would silently not match.
from ha_mcp._vendor.websockets.exceptions import (
ConnectionClosed,
InvalidHandshake,
InvalidStatus,
)
from ha_mcp.tools.tools_addons import (
_apply_response_transform,
_call_addon_api,
_call_addon_ws,
_extract_addon_log_level,
_is_signal_message,
_slice_ws_messages,
_summarize_ws_messages,
get_addon_info,
list_addons,
)
# Standard mock return for a running addon with Ingress support
_RUNNING_ADDON_INFO = {
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": True,
"state": "started",
"ingress_entry": "/api/hassio_ingress/abc123",
"ip_address": "172.30.33.99",
"ingress_port": 5000,
},
}
_INGRESS_SESSION_TOKEN = "test-ingress-session"
_FRONT_DOOR_SCHEMA = [
{"name": "leave_front_door_open", "type": "boolean", "optional": True}
]
def _front_door_fixture(front_door) -> tuple[dict, list]:
"""Return (options, schema) for one leave_front_door_open state.
False/True: option saved with that value. "absent": exposed in the schema
but never saved (stock install). "unexposed": app without the option.
"""
if front_door == "unexposed":
return {}, []
if front_door == "absent":
return {}, list(_FRONT_DOOR_SCHEMA)
return {"leave_front_door_open": front_door}, list(_FRONT_DOOR_SCHEMA)
def _make_mock_client() -> MagicMock:
"""Create a mock HomeAssistantClient."""
client = MagicMock()
client.base_url = "http://localhost:8123"
client.token = "test-token"
client.verify_ssl = True
return client
def _parse_tool_error(exc_info: pytest.ExceptionInfo[ToolError]) -> dict:
"""Parse the JSON payload from a ToolError."""
return json.loads(str(exc_info.value))
@pytest.fixture(autouse=True)
def _default_offhost_env(monkeypatch):
"""Pin tests to the off-host install variant by default.
`is_running_in_addon()` reads `SUPERVISOR_TOKEN` from the environment.
Without explicit pinning, a test inheriting that env var from the host
shell would silently flip into the HA-add-on branch and assert the wrong
route. Tests exercising the addon variant must `monkeypatch.setenv`
inside their body to override this default.
"""
monkeypatch.delenv("SUPERVISOR_TOKEN", raising=False)
@pytest.fixture
def mock_ingress_session():
"""Patch _create_ingress_session to return a fixed token without WS calls."""
with patch(
"ha_mcp.tools.tools_addons._create_ingress_session",
new_callable=AsyncMock,
return_value=_INGRESS_SESSION_TOKEN,
) as m:
yield m
class TestCallAddonApiErrors:
"""Tests for _call_addon_api error paths."""
@pytest.mark.asyncio
async def test_path_traversal_rejected(self):
"""Paths containing '..' components should be rejected."""
client = _make_mock_client()
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "../../etc/passwd")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert (
"traversal" in result["error"]["message"].lower()
or ".." in result["error"]["message"]
)
@pytest.mark.asyncio
async def test_path_traversal_middle_segment(self):
"""Paths with '..' in the middle should also be rejected."""
client = _make_mock_client()
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "api/../secret/data")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert ".." in result["error"]["message"]
@pytest.mark.asyncio
async def test_path_with_dotdot_in_name_allowed(self):
"""Paths where '..' is part of a filename (not a segment) should pass traversal check."""
client = _make_mock_client()
# "..foo" is not a ".." path segment, so it should pass the traversal check
# but it will fail on the addon info lookup (next step)
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": False,
"error": {"code": "RESOURCE_NOT_FOUND", "message": "Not found"},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "..foo/bar")
# Should have passed traversal check and failed on addon lookup instead
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert "Not found" in result["error"]["message"]
@pytest.mark.asyncio
async def test_addon_not_found(self):
"""Should raise ToolError when add-on slug doesn't exist."""
client = _make_mock_client()
error_response = {
"success": False,
"error": {
"code": "RESOURCE_NOT_FOUND",
"message": "Add-on 'fake_addon' not found",
},
}
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=error_response,
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "fake_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert "not found" in result["error"]["message"].lower()
@pytest.mark.asyncio
async def test_addon_no_ingress_support(self):
"""Should raise ToolError when add-on doesn't support Ingress."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": False,
"state": "started",
},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert "ingress" in result["error"]["message"].lower()
@pytest.mark.asyncio
async def test_addon_not_running(self):
"""Should raise ToolError when add-on is not running."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": True,
"state": "stopped",
"ingress_entry": "/api/hassio_ingress/abc123",
},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert "not running" in result["error"]["message"].lower()
assert "stopped" in result["error"]["message"]
@pytest.mark.asyncio
async def test_addon_no_ingress_entry(self):
"""Should raise ToolError when add-on has Ingress but no entry path."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": True,
"state": "started",
"ingress_entry": "",
},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert (
"ingress_entry" in result["error"]["message"].lower()
or "ingress" in result["error"]["message"].lower()
)
@pytest.mark.asyncio
async def test_direct_port_missing_ip_address(self):
"""Direct-port mode requires the addon's container ip_address."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": False,
"state": "started",
"ip_address": "",
},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "/flows", port=1880)
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert "ip_address" in str(result).lower()
@pytest.mark.asyncio
async def test_http_timeout(self, mock_ingress_session):
"""Should raise ToolError when add-on API doesn't respond."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.TimeoutException("timed out")
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/api/test", timeout=5)
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert (
"timeout" in result["error"]["message"].lower()
or "timed out" in str(result).lower()
)
@pytest.mark.asyncio
async def test_http_connection_error(self, mock_ingress_session):
"""Should raise ToolError when can't reach add-on."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.ConnectError(
"Connection refused"
)
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["success"] is False
assert (
"connect" in result["error"]["message"].lower()
or "connection" in str(result).lower()
)
@pytest.mark.asyncio
async def test_http_ingress_routes_through_ha_core(self, mock_ingress_session):
"""Ingress mode targets HA Core's /api/hassio_ingress proxy with a session cookie."""
client = _make_mock_client()
captured: dict[str, object] = {}
async def fake_request(*, method, url, headers, content):
captured["method"] = method
captured["url"] = url
captured["headers"] = dict(headers)
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {"ok": True}
response.text = '{"ok": true}'
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/api/test")
assert result["success"] is True
# URL is HA Core's ingress proxy, NOT the addon container IP
assert captured["url"] == (
"http://localhost:8123/api/hassio_ingress/abc123/api/test"
)
# Session cookie attached
headers = captured["headers"]
assert headers["Cookie"] == f"ingress_session={_INGRESS_SESSION_TOKEN}"
# Direct-container Ingress headers MUST NOT be set — HA Core adds them
# itself when it proxies upstream, and adding our own would conflict.
assert "X-Ingress-Path" not in headers
assert "X-Hass-Source" not in headers
# Bearer would be forwarded to the add-on upstream — leak vector.
assert "Authorization" not in headers
# Ingress session was minted exactly once
mock_ingress_session.assert_awaited_once()
@pytest.mark.asyncio
async def test_http_direct_port_skips_ingress_session(self, mock_ingress_session):
"""Direct-port mode connects to container IP and does not mint an ingress session."""
client = _make_mock_client()
captured: dict[str, object] = {}
async def fake_request(*, method, url, headers, content):
captured["url"] = url
captured["headers"] = dict(headers)
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {"ok": True}
response.text = '{"ok": true}'
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/flows", port=1880)
assert result["success"] is True
assert captured["url"] == "http://172.30.33.99:1880/flows"
assert "Cookie" not in captured["headers"]
mock_ingress_session.assert_not_awaited()
@pytest.mark.asyncio
async def test_http_direct_port_offhost_error_hints_at_ingress(
self, mock_ingress_session
):
"""ConnectError in direct-port mode should suggest dropping `port` for off-host hosts."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.ConnectError(
"No route to host"
)
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/flows", port=1880)
result = _parse_tool_error(exc_info)
suggestions = result["error"].get("suggestions", [])
assert any("ingress" in s.lower() for s in suggestions), suggestions
@pytest.mark.asyncio
async def test_http_direct_port_timeout_hints_at_ingress(
self, mock_ingress_session
):
"""Timeouts in direct-port mode should also suggest dropping `port`.
On real off-host installs, packets to the addon's container IP often
get silently dropped by the upstream router instead of refused —
which surfaces as TimeoutException, not ConnectError. The same
actionable hint must apply.
"""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.TimeoutException(
"Connection timed out"
)
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(
client, "test_addon", "/flows", port=1880, timeout=5
)
result = _parse_tool_error(exc_info)
suggestions = result["error"].get("suggestions", [])
assert any("ingress" in s.lower() for s in suggestions), suggestions
@pytest.mark.asyncio
async def test_http_ingress_timeout_hints_at_ha_core(self, mock_ingress_session):
"""Timeouts in ingress mode should point at HA Core, not the add-on."""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.TimeoutException("timed out")
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/api/test", timeout=5)
result = _parse_tool_error(exc_info)
suggestions = result["error"].get("suggestions", [])
assert any(client.base_url in s for s in suggestions), suggestions
assert not any("'port' parameter" in s for s in suggestions), suggestions
@pytest.mark.asyncio
async def test_http_ingress_connection_error_hints_at_ha_core(
self, mock_ingress_session
):
"""ConnectError in ingress mode should point at HA Core, not the add-on.
The actual failure on off-host installs is HA Core unreachable from
the MCP host — the old generic "Check that the add-on is running"
hint sent users on a wild-goose chase.
"""
client = _make_mock_client()
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.ConnectError(
"Connection refused"
)
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
suggestions = result["error"].get("suggestions", [])
# Suggestion should reference the configured HA URL so the user
# knows where to verify reachability.
assert any(client.base_url in s for s in suggestions), suggestions
# Direct-port-only hint must not surface in ingress-mode failures.
assert not any("'port' parameter" in s for s in suggestions), suggestions
@pytest.mark.asyncio
async def test_http_base_url_with_trailing_slash(self, mock_ingress_session):
"""Trailing slash on base_url must not produce a doubled slash in the request URL."""
client = _make_mock_client()
client.base_url = "http://localhost:8123/"
captured: dict[str, object] = {}
async def fake_request(*, method, url, headers, content):
captured["url"] = url
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {"ok": True}
response.text = '{"ok": true}'
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
await _call_addon_api(client, "test_addon", "/api/test")
assert captured["url"] == (
"http://localhost:8123/api/hassio_ingress/abc123/api/test"
)
@pytest.mark.asyncio
async def test_http_addon_variant_uses_direct_ingress_port(
self, monkeypatch, mock_ingress_session
):
"""When running as the HA add-on, ingress mode hits the addon's container
directly with `core.ingress` source headers — no HA Core proxy hop, no
session cookie. This is the path that worked on master pre-PR."""
monkeypatch.setenv("SUPERVISOR_TOKEN", "supervisor-test-token")
client = _make_mock_client()
# Inside the addon variant, base_url points at Supervisor's proxy mount.
client.base_url = "http://supervisor/core"
captured: dict[str, object] = {}
async def fake_request(*, method, url, headers, content):
captured["url"] = url
captured["headers"] = dict(headers)
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {"ok": True}
response.text = '{"ok": true}'
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/api/test")
assert result["success"] is True
# URL is the addon container's ingress port — NOT the HA Core proxy.
assert captured["url"] == "http://172.30.33.99:5000/api/test"
headers = captured["headers"]
# Source-trust headers, the way master routed pre-PR.
assert headers["X-Ingress-Path"] == "/api/hassio_ingress/abc123"
assert headers["X-Hass-Source"] == "core.ingress"
# No HA-Core-side auth — not going through Core.
assert "Cookie" not in headers
assert "Authorization" not in headers
# No ingress session minted on the addon variant.
mock_ingress_session.assert_not_awaited()
@pytest.mark.asyncio
async def test_http_addon_variant_missing_ingress_port_errors(self, monkeypatch):
"""Addon variant requires both ip_address and ingress_port."""
monkeypatch.setenv("SUPERVISOR_TOKEN", "supervisor-test-token")
client = _make_mock_client()
client.base_url = "http://supervisor/core"
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value={
"success": True,
"addon": {
"name": "Test Addon",
"slug": "test_addon",
"ingress": True,
"state": "started",
"ingress_entry": "/api/hassio_ingress/abc123",
"ip_address": "172.30.33.99",
"ingress_port": None,
},
},
),
pytest.raises(ToolError) as exc_info,
):
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
assert result["error"]["code"] == "INTERNAL_ERROR"
assert "ingress_port" in str(result).lower()
@pytest.mark.asyncio
async def test_http_addon_variant_connect_error_hints_at_addon_network(
self, monkeypatch, mock_ingress_session
):
"""ConnectError on addon variant should suggest restarting the target
add-on, not 'verify HA reachable' (HA is fine — sibling network is the
problem)."""
monkeypatch.setenv("SUPERVISOR_TOKEN", "supervisor-test-token")
client = _make_mock_client()
client.base_url = "http://supervisor/core"
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = httpx.ConnectError(
"No route to host"
)
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/api/test")
result = _parse_tool_error(exc_info)
suggestions = result["error"].get("suggestions", [])
# Addon-variant suggestion should be about the target add-on / addon
# network — not about HA Core reachability.
assert any(
"restart" in s.lower() or "addon network" in s.lower() for s in suggestions
), suggestions
# The off-host hint about HA Core reachability must NOT appear here.
assert not any(client.base_url in s for s in suggestions), suggestions
@pytest.mark.asyncio
async def test_http_401_response_hints_at_auth(self, mock_ingress_session):
"""A 401 from the add-on points at auth/token/session, NOT at IP
restriction. addon_config is dropped because it's a credential
problem, not a misconfigured add-on."""
client = _make_mock_client()
async def fake_request(*, method, url, headers, content):
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 401
response.json.return_value = {}
response.text = "{}"
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/api/test")
assert result["status_code"] == 401
suggestion = result["suggestion"].lower()
# Auth-flavored hint expected.
assert any(
token in suggestion for token in ("auth", "token", "scope", "session")
), result["suggestion"]
# IP-restriction hint must NOT fire on 401 — it would misdirect.
assert "nginx" not in suggestion, result["suggestion"]
assert "ip restriction" not in suggestion, result["suggestion"]
# addon_config is irrelevant for a credential problem.
assert "addon_config" not in result, result
@pytest.mark.asyncio
@pytest.mark.parametrize("status", [401, 403])
@pytest.mark.parametrize("front_door", [False, True, "absent", "unexposed"])
async def test_http_direct_port_auth_hints_at_app_option(self, status, front_door):
"""Direct auth errors suggest the option only when it is off.
"absent" mirrors a stock install: the option lives in the schema but
was never saved, so Supervisor omits it from options — the app treats
that as disabled. "unexposed" is an app without the option at all.
"""
options, schema = _front_door_fixture(front_door)
client = _make_mock_client()
addon_info = {
"success": True,
"addon": {
**_RUNNING_ADDON_INFO["addon"],
"options": options,
"schema": schema,
"ports": {"1880/tcp": 1880},
},
}
async def fake_request(*, method, url, headers, content):
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = status
response.json.return_value = {}
response.text = "{}"
return response
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=addon_info,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = fake_request
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/flows", port=1880)
assert result["status_code"] == status
suggestion = result["suggestion"]
if front_door in (True, "unexposed"):
assert "options={'leave_front_door_open': True}" not in suggestion
assert "app's own authentication" in suggestion
assert "access-control" in suggestion
assert "ingress session" not in suggestion.lower()
assert "HA token" not in suggestion
else:
assert result["addon_config"]["options"] == options
assert "leave_front_door_open" in suggestion
assert "ha_manage_app" in suggestion
assert "restart" in suggestion.lower()
assert "action='restart'" in suggestion
assert "security" in suggestion.lower()
@pytest.mark.asyncio
async def test_http_proxy_propagates_tls_verification(self, mock_ingress_session):
"""The add-on proxy must honor the HA client's TLS verification setting."""
client = _make_mock_client()
client.base_url = "https://ha.local:8123"
client.verify_ssl = False
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {}
response.text = "{}"
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.return_value = response
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/flows")
assert result["success"] is True
assert mock_httpx.call_args.kwargs["verify"] is False
@pytest.mark.asyncio
async def test_http_proxy_keeps_tls_verification_by_default(
self, mock_ingress_session
):
"""verify_ssl=True must reach httpx unchanged — the secure default."""
client = _make_mock_client()
client.base_url = "https://ha.local:8123"
client.verify_ssl = True
response = MagicMock()
response.headers = {"content-type": "application/json"}
response.status_code = 200
response.json.return_value = {}
response.text = "{}"
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.return_value = response
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
result = await _call_addon_api(client, "test_addon", "/flows")
assert result["success"] is True
assert mock_httpx.call_args.kwargs["verify"] is True
@pytest.mark.asyncio
async def test_http_proxy_classifies_tls_verification_failure(
self, mock_ingress_session
):
"""A cert failure with verification on names the TLS remedy."""
client = _make_mock_client()
client.base_url = "https://ha.local:8123"
client.verify_ssl = True
connect_error = httpx.ConnectError("All connection attempts failed")
connect_error.__cause__ = ssl.SSLCertVerificationError(
"certificate verify failed: IP address mismatch"
)
with (
patch(
"ha_mcp.tools.tools_addons.get_addon_info",
new_callable=AsyncMock,
return_value=_RUNNING_ADDON_INFO,
),
patch(
"ha_mcp.tools.tools_addons.httpx.AsyncClient",
) as mock_httpx,
):
mock_http_client = AsyncMock()
mock_http_client.request.side_effect = connect_error
mock_httpx.return_value.__aenter__ = AsyncMock(
return_value=mock_http_client
)
mock_httpx.return_value.__aexit__ = AsyncMock(return_value=False)
with pytest.raises(ToolError) as exc_info:
await _call_addon_api(client, "test_addon", "/flows")
result = _parse_tool_error(exc_info)
assert "TLS verification failed" in result["error"]["message"]
# A single suggestion lands under the singular key.
joined = " ".join(
[
result["error"].get("suggestion", ""),
*result["error"].get("suggestions", []),
]
)