|
| 1 | +"""Invariant: an adapter's endpoint/identity resolves through the SAME profile scope as its secret. |
| 2 | +
|
| 3 | +Under ``gateway.multiplex_profiles`` ``os.environ`` holds the DEFAULT profile's values; a secondary |
| 4 | +profile's ``.env`` exists only in its secret scope. Every adapter here already read its *secret* |
| 5 | +scope-aware but read the paired homeserver / URL / client_id / from-number / webhook URL raw from |
| 6 | +``os.environ`` — so the secondary's credential was sent to the default profile's host or identity. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import os |
| 12 | +from unittest.mock import AsyncMock, MagicMock |
| 13 | + |
| 14 | +import pytest |
| 15 | + |
| 16 | +from agent import secret_scope as ss |
| 17 | +from gateway.config import PlatformConfig |
| 18 | +from tests.gateway._plugin_adapter_loader import load_plugin_adapter |
| 19 | + |
| 20 | +DEFAULT_ENV = { |
| 21 | + "MATRIX_HOMESERVER": "https://default.matrix.example", "MATRIX_USER_ID": "@default:example", |
| 22 | + "MATRIX_DEVICE_ID": "DEFAULTDEV", "MATRIX_ACCESS_TOKEN": "default-matrix-token", |
| 23 | + "HASS_URL": "http://default-ha.example:8123", "HASS_TOKEN": "default-ha-token", |
| 24 | + "TEAMS_CLIENT_ID": "default-client-id", "TEAMS_TENANT_ID": "default-tenant", |
| 25 | + "TEAMS_CLIENT_SECRET": "default-teams-secret", "TEAMS_HOME_CHANNEL": "default-conv", |
| 26 | + "DINGTALK_CLIENT_ID": "default-ding-id", "DINGTALK_CLIENT_SECRET": "default-ding-secret", |
| 27 | + "DINGTALK_WEBHOOK_URL": "https://oapi.dingtalk.com/robot/send?access_token=DEFAULT", |
| 28 | + "TELEGRAM_WEBHOOK_URL": "https://default.example/tg", |
| 29 | +} |
| 30 | +SECONDARY = { |
| 31 | + "MATRIX_HOMESERVER": "https://bot2.matrix.example", "MATRIX_USER_ID": "@bot2:example", |
| 32 | + "MATRIX_DEVICE_ID": "BOT2DEV", "MATRIX_ACCESS_TOKEN": "bot2-matrix-token", |
| 33 | + "HASS_URL": "http://bot2-ha.example:8123", "HASS_TOKEN": "bot2-ha-token", |
| 34 | + "TEAMS_CLIENT_ID": "bot2-client-id", "TEAMS_TENANT_ID": "bot2-tenant", |
| 35 | + "TEAMS_CLIENT_SECRET": "bot2-teams-secret", "TEAMS_HOME_CHANNEL": "bot2-conv", |
| 36 | + "DINGTALK_CLIENT_ID": "bot2-ding-id", "DINGTALK_CLIENT_SECRET": "bot2-ding-secret", |
| 37 | + "DINGTALK_WEBHOOK_URL": "https://oapi.dingtalk.com/robot/send?access_token=BOT2", |
| 38 | + "TELEGRAM_WEBHOOK_URL": "https://bot2.example/tg", |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +@pytest.fixture |
| 43 | +def secondary_scope(monkeypatch): |
| 44 | + """Default profile in os.environ, multiplex on, secondary profile's scope installed.""" |
| 45 | + for key, value in DEFAULT_ENV.items(): |
| 46 | + monkeypatch.setenv(key, value) |
| 47 | + ss.set_multiplex_active(True) |
| 48 | + token = ss.set_secret_scope(SECONDARY) |
| 49 | + yield |
| 50 | + ss.reset_secret_scope(token) |
| 51 | + ss.set_multiplex_active(False) |
| 52 | + |
| 53 | + |
| 54 | +def test_matrix_homeserver_identity_follow_the_scoped_token(secondary_scope): |
| 55 | + from plugins.platforms.matrix.adapter import MatrixAdapter |
| 56 | + |
| 57 | + adapter = MatrixAdapter(PlatformConfig(enabled=True)) |
| 58 | + assert adapter._access_token == SECONDARY["MATRIX_ACCESS_TOKEN"] |
| 59 | + assert (adapter._homeserver, adapter._user_id, adapter._device_id) == ( |
| 60 | + SECONDARY["MATRIX_HOMESERVER"], SECONDARY["MATRIX_USER_ID"], SECONDARY["MATRIX_DEVICE_ID"]) |
| 61 | + |
| 62 | + |
| 63 | +@pytest.mark.asyncio |
| 64 | +async def test_matrix_standalone_send_posts_scoped_token_to_scoped_homeserver(secondary_scope, monkeypatch): |
| 65 | + import aiohttp |
| 66 | + from plugins.platforms.matrix import adapter as mx |
| 67 | + |
| 68 | + seen = {} |
| 69 | + |
| 70 | + class _Resp: |
| 71 | + status = 200 |
| 72 | + async def __aenter__(self): return self |
| 73 | + async def __aexit__(self, *a): return False |
| 74 | + async def json(self): return {"event_id": "$x"} |
| 75 | + async def text(self): return "" |
| 76 | + |
| 77 | + class _Sess: |
| 78 | + def __init__(self, *a, **k): pass |
| 79 | + async def __aenter__(self): return self |
| 80 | + async def __aexit__(self, *a): return False |
| 81 | + def put(self, url, **kw): seen["url"] = url; seen["headers"] = kw.get("headers", {}); return _Resp() |
| 82 | + |
| 83 | + monkeypatch.setattr(aiohttp, "ClientSession", _Sess) |
| 84 | + await mx._standalone_send(PlatformConfig(enabled=True), "!room:example", "hi") |
| 85 | + assert seen["url"].startswith(SECONDARY["MATRIX_HOMESERVER"] + "/") |
| 86 | + assert DEFAULT_ENV["MATRIX_HOMESERVER"] not in seen["url"] |
| 87 | + |
| 88 | + |
| 89 | +def test_homeassistant_url_follows_the_scoped_token(secondary_scope): |
| 90 | + from plugins.platforms.homeassistant.adapter import HomeAssistantAdapter |
| 91 | + |
| 92 | + adapter = HomeAssistantAdapter(PlatformConfig(enabled=True)) |
| 93 | + assert (adapter._hass_url, adapter._hass_token) == (SECONDARY["HASS_URL"], SECONDARY["HASS_TOKEN"]) |
| 94 | + |
| 95 | + |
| 96 | +@pytest.mark.asyncio |
| 97 | +async def test_homeassistant_standalone_send_targets_scoped_url(secondary_scope, monkeypatch): |
| 98 | + import aiohttp |
| 99 | + from plugins.platforms.homeassistant import adapter as ha |
| 100 | + |
| 101 | + seen = {} |
| 102 | + |
| 103 | + class _Resp: |
| 104 | + status = 200 |
| 105 | + async def __aenter__(self): return self |
| 106 | + async def __aexit__(self, *a): return False |
| 107 | + async def text(self): return "" |
| 108 | + |
| 109 | + class _Sess: |
| 110 | + def __init__(self, *a, **k): pass |
| 111 | + async def __aenter__(self): return self |
| 112 | + async def __aexit__(self, *a): return False |
| 113 | + def post(self, url, **kw): seen["url"] = url; return _Resp() |
| 114 | + |
| 115 | + monkeypatch.setattr(aiohttp, "ClientSession", _Sess) |
| 116 | + await ha._standalone_send(PlatformConfig(enabled=True), "x", "hi") |
| 117 | + assert seen["url"].startswith(SECONDARY["HASS_URL"] + "/") |
| 118 | + |
| 119 | + |
| 120 | +def test_teams_credentials_pair_scoped_secret_with_scoped_app_identity(secondary_scope): |
| 121 | + teams = load_plugin_adapter("teams") |
| 122 | + assert teams._credentials(PlatformConfig(enabled=True)) == ( |
| 123 | + SECONDARY["TEAMS_CLIENT_ID"], SECONDARY["TEAMS_CLIENT_SECRET"], SECONDARY["TEAMS_TENANT_ID"]) |
| 124 | + # extra (per-profile config.yaml) must win over any env value. |
| 125 | + assert teams._credentials(PlatformConfig(enabled=True, extra={"client_id": "yaml-id"}))[0] == "yaml-id" |
| 126 | + |
| 127 | + |
| 128 | +def test_teams_env_enablement_seeds_scoped_identity_and_home_channel(secondary_scope): |
| 129 | + teams = load_plugin_adapter("teams") |
| 130 | + seed = teams._env_enablement() |
| 131 | + assert seed["client_id"] == SECONDARY["TEAMS_CLIENT_ID"] |
| 132 | + assert seed["home_channel"]["chat_id"] == SECONDARY["TEAMS_HOME_CHANNEL"] |
| 133 | + |
| 134 | + |
| 135 | +def test_dingtalk_client_id_follows_the_scoped_secret(secondary_scope): |
| 136 | + from plugins.platforms.dingtalk.adapter import _credentials |
| 137 | + |
| 138 | + assert _credentials(None) == (SECONDARY["DINGTALK_CLIENT_ID"], SECONDARY["DINGTALK_CLIENT_SECRET"]) |
| 139 | + |
| 140 | + |
| 141 | +@pytest.mark.asyncio |
| 142 | +async def test_dingtalk_standalone_send_posts_to_scoped_robot_webhook(secondary_scope, monkeypatch): |
| 143 | + import httpx |
| 144 | + from plugins.platforms.dingtalk import adapter as ding |
| 145 | + |
| 146 | + posted = [] |
| 147 | + |
| 148 | + class _Resp: |
| 149 | + def raise_for_status(self): pass |
| 150 | + def json(self): return {"errcode": 0} |
| 151 | + |
| 152 | + class _Client: |
| 153 | + def __init__(self, *a, **k): pass |
| 154 | + async def __aenter__(self): return self |
| 155 | + async def __aexit__(self, *a): return False |
| 156 | + async def post(self, url, **kw): posted.append(url); return _Resp() |
| 157 | + |
| 158 | + monkeypatch.setattr(httpx, "AsyncClient", _Client) |
| 159 | + result = await ding._standalone_send(PlatformConfig(enabled=True), "c", "hi") |
| 160 | + assert result.get("success") is True |
| 161 | + assert posted == [SECONDARY["DINGTALK_WEBHOOK_URL"]] |
| 162 | + |
| 163 | + |
| 164 | +@pytest.mark.asyncio |
| 165 | +async def test_telegram_connect_registers_scoped_webhook_url(secondary_scope, monkeypatch): |
| 166 | + from plugins.platforms.telegram import adapter as tg |
| 167 | + |
| 168 | + class _Builder: |
| 169 | + def __getattr__(self, name): |
| 170 | + return lambda *a, **k: self |
| 171 | + def build(self): |
| 172 | + app = MagicMock(); app.bot = MagicMock(); app.start = AsyncMock(); app.initialize = AsyncMock() |
| 173 | + return app |
| 174 | + |
| 175 | + monkeypatch.setattr(tg, "Application", type("_App", (), {"builder": staticmethod(_Builder)})) |
| 176 | + adapter = tg.TelegramAdapter(PlatformConfig(enabled=True, token="bot2-token")) |
| 177 | + for name in ("_wire_plugin_handlers", "_register_handlers", "_mark_connected", "_start_post_connect_housekeeping"): |
| 178 | + monkeypatch.setattr(adapter, name, MagicMock()) |
| 179 | + monkeypatch.setattr(adapter, "_acquire_platform_lock", lambda *a, **k: True) |
| 180 | + monkeypatch.setattr(adapter, "_build_ptb_requests", AsyncMock(return_value=(MagicMock(), MagicMock()))) |
| 181 | + monkeypatch.setattr(adapter, "_initialize_app_with_retries", AsyncMock()) |
| 182 | + seen = {} |
| 183 | + |
| 184 | + async def _webhook(url, *, is_reconnect): seen["url"] = url |
| 185 | + async def _polling(*, is_reconnect): seen["url"] = "<polling>" |
| 186 | + |
| 187 | + monkeypatch.setattr(adapter, "_start_webhook_mode", _webhook) |
| 188 | + monkeypatch.setattr(adapter, "_start_polling_mode", _polling) |
| 189 | + assert await adapter.connect() is True |
| 190 | + assert seen["url"] == SECONDARY["TELEGRAM_WEBHOOK_URL"] |
| 191 | + assert os.environ["TELEGRAM_WEBHOOK_URL"] == DEFAULT_ENV["TELEGRAM_WEBHOOK_URL"] # env untouched; scope won |
0 commit comments