Skip to content

Commit e253ea0

Browse files
teknium1nftpoetrist
andcommitted
fix(gateway): secondary-profile adapters no longer send their credentials to the default profile's host/identity
Under gateway.multiplex_profiles, os.environ holds the DEFAULT profile's values and a secondary profile's .env exists only in its secret scope. Matrix, Home Assistant, Teams, DingTalk, SMS and Telegram already read their *secret* scope-aware, but read the paired endpoint/identity raw from os.environ — so a secondary's token/secret/password was paired with the default profile's host or app identity: - Matrix: MATRIX_HOMESERVER / MATRIX_USER_ID / MATRIX_DEVICE_ID in __init__ and MATRIX_HOMESERVER in _standalone_send -> the secondary's access token was sent to the default's homeserver (and its E2EE device id reused). - Home Assistant: HASS_URL in __init__ and _standalone_send -> the secondary's HASS_TOKEN was posted to the default's HA instance. - Teams: TEAMS_CLIENT_ID / TEAMS_TENANT_ID (env-first, even over extra), TEAMS_SERVICE_URL, TEAMS_HOME_CHANNEL(_NAME) in _credentials, _env_enablement, _standalone_send and __init__ -> Bot Framework token requested for the default's app with the secondary's secret; cron home channel was the default's conversation. - DingTalk: DINGTALK_CLIENT_ID in _credentials, DINGTALK_WEBHOOK_URL in _standalone_send -> wrong app id; cron output posted to the default's robot webhook (URL carries its access_token). - Telegram: TELEGRAM_WEBHOOK_URL in connect() -> the default's public webhook URL registered on the secondary bot, mixing update traffic. Each read now goes through the same scoped reader its sibling secret already uses (_get_scoped_secret / _startup_env_secret / get_secret with the UnscopedSecretError fallback), so a scoped miss is empty rather than the default profile's value; the unscoped default-profile path and single-profile deployments keep reading os.environ, which there IS the profile's own value. Teams _credentials now lets extra (per-profile config.yaml) win over env, matching every other adapter and its own __init__. Live repro (/tmp/mux_audit/fix-endpoint-identity/repro.py, secondary scope "bot2" with the default profile in os.environ): 19 of 24 reads returned the default's endpoint/identity before; 0 after. Salvage: SMS from-number fix cherry-picked from #100625 (tests trimmed to two invariants). Teams identity (#100622) and DingTalk (#100615) reimplemented on the minimal shape — the Teams PR added a _profile_scoped() gate to _env_enablement and the DingTalk PR only covered the YAML bridge, not DINGTALK_CLIENT_ID / DINGTALK_WEBHOOK_URL. Matrix, Home Assistant and Telegram parts have no prior PR. Co-authored-by: nftpoetrist <264138787+nftpoetrist@users.noreply.github.com>
1 parent 8099745 commit e253ea0

6 files changed

Lines changed: 240 additions & 23 deletions

File tree

‎plugins/platforms/dingtalk/adapter.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,10 @@ def ensure_dingtalk_deps() -> bool:
116116
def _credentials(extra: Optional[dict]) -> tuple:
117117
"""(client_id, client_secret) from PlatformConfig.extra first, then env / scoped secret."""
118118
extra = extra or {}
119-
return (extra.get("client_id") or os.getenv("DINGTALK_CLIENT_ID", ""), extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
119+
# client_id goes through the same scoped reader as the secret: os.environ holds the DEFAULT
120+
# profile's app id under multiplex, and pairing it with a secondary's secret authenticates as the wrong app.
121+
return (extra.get("client_id") or _get_scoped_secret("DINGTALK_CLIENT_ID", ""),
122+
extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
120123

121124

122125
def check_dingtalk_requirements() -> bool:
@@ -627,7 +630,9 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
627630
import httpx
628631
except ImportError:
629632
return {"error": "httpx not installed"}
630-
webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or os.getenv("DINGTALK_WEBHOOK_URL", "")
633+
# Scoped: the webhook URL carries the robot's access_token and IS the delivery target — a raw
634+
# environ read would post a secondary profile's cron output to the default profile's robot.
635+
webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or _get_scoped_secret("DINGTALK_WEBHOOK_URL", "")
631636
if not webhook_url:
632637
return {"error": "DingTalk not configured. Set DINGTALK_WEBHOOK_URL env var or webhook_url in dingtalk platform extra config."}
633638
try:

‎plugins/platforms/homeassistant/adapter.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ def __init__(self, config: PlatformConfig):
7777
self._listen_task: Optional[asyncio.Task] = None
7878
self._msg_id: int = 0
7979
extra = config.extra or {}
80-
self._hass_url: str = (extra.get("url") or os.getenv("HASS_URL", "http://homeassistant.local:8123")).rstrip("/")
80+
# URL is scoped like the token below: a secondary's HASS_TOKEN must never be posted to the
81+
# DEFAULT profile's HA instance (os.environ under multiplex).
82+
self._hass_url: str = (extra.get("url") or _get_scoped_secret("HASS_URL", "http://homeassistant.local:8123")).rstrip("/")
8183
self._hass_token: str = config.token or _get_scoped_secret("HASS_TOKEN", "")
8284
self._watch_domains: Set[str] = set(extra.get("watch_domains", []))
8385
self._watch_entities: Set[str] = set(extra.get("watch_entities", []))
@@ -317,7 +319,7 @@ async def _standalone_send(
317319
if not AIOHTTP_AVAILABLE:
318320
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
319321
extra = getattr(pconfig, "extra", {}) or {}
320-
hass_url = (extra.get("url") or os.getenv("HASS_URL", "")).rstrip("/")
322+
hass_url = (extra.get("url") or _get_scoped_secret("HASS_URL", "")).rstrip("/")
321323
token = (getattr(pconfig, "token", None) or _get_scoped_secret("HASS_TOKEN", "")).strip()
322324
if not hass_url or not token:
323325
return {"error": "Home Assistant standalone send: HASS_URL and HASS_TOKEN must both be set"}

‎plugins/platforms/matrix/adapter.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -815,13 +815,17 @@ def __init__(self, config: PlatformConfig):
815815
self.MAX_MESSAGE_LENGTH = self.max_message_length # mirrors other adapters for tooling
816816
# A chunk near the outbound limit almost certainly has a continuation.
817817
self._split_threshold = max(100, self.max_message_length - 100)
818-
self._homeserver: str = (config.extra.get("homeserver", "") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/")
818+
# Homeserver/user_id/device_id go through the same scoped reader as the token/password:
819+
# under multiplex os.environ holds the DEFAULT profile's identity, and pairing it with a
820+
# secondary's credential sends that credential to the wrong homeserver (or reuses the
821+
# default's E2EE device id).
822+
self._homeserver: str = (config.extra.get("homeserver", "") or _startup_env_secret("MATRIX_HOMESERVER")).rstrip("/")
819823
self._access_token: str = config.token or _startup_env_secret("MATRIX_ACCESS_TOKEN")
820-
self._user_id: str = config.extra.get("user_id", "") or os.getenv("MATRIX_USER_ID", "")
824+
self._user_id: str = config.extra.get("user_id", "") or _startup_env_secret("MATRIX_USER_ID")
821825
self._password: str = config.extra.get("password", "") or _startup_env_secret("MATRIX_PASSWORD")
822826
self._e2ee_mode: str = _resolve_e2ee_mode(config.extra)
823827
self._encryption: bool = self._e2ee_mode != "off"
824-
self._device_id: str = config.extra.get("device_id", "") or os.getenv("MATRIX_DEVICE_ID", "")
828+
self._device_id: str = config.extra.get("device_id", "") or _startup_env_secret("MATRIX_DEVICE_ID")
825829
self._device_id_unverified: bool = False
826830
self._client: Any = None # mautrix.client.Client
827831
self._crypto_db: Any = None # mautrix.util.async_db.Database
@@ -2912,8 +2916,9 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
29122916
except ImportError:
29132917
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
29142918
try:
2915-
homeserver = (extra.get("homeserver") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/")
2916-
# In-turn read inside an installed secret scope: honor get_secret, no env fallback.
2919+
# In-turn reads inside an installed secret scope: honor get_secret, no env fallback — for the
2920+
# homeserver too, so the scoped token is never sent to the default profile's server.
2921+
homeserver = (extra.get("homeserver") or get_secret("MATRIX_HOMESERVER", "") or "").rstrip("/")
29172922
token = getattr(pconfig, "token", None) or get_secret("MATRIX_ACCESS_TOKEN", "") or ""
29182923
if not homeserver or not token:
29192924
return {"error": "Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)"}

‎plugins/platforms/teams/adapter.py‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -144,12 +144,18 @@ def check_requirements() -> bool:
144144

145145

146146
def _credentials(config) -> tuple[str, str, str]:
147-
"""(client_id, client_secret, tenant_id): env first, then ``config.extra``."""
147+
"""(client_id, client_secret, tenant_id): ``config.extra`` first, then the profile-scoped env.
148+
149+
client_id/tenant_id are read through the same scoped reader as the secret: under multiplex,
150+
``os.environ`` holds the DEFAULT profile's app identity, and pairing it with a secondary's
151+
secret requests a Bot Framework token for the wrong app. ``extra`` wins so a per-profile
152+
config.yaml identity is never overridden by the process env.
153+
"""
148154
extra = getattr(config, "extra", {}) or {}
149155
return (
150-
os.getenv("TEAMS_CLIENT_ID") or extra.get("client_id", ""),
151-
_get_scoped_secret("TEAMS_CLIENT_SECRET") or extra.get("client_secret", ""),
152-
os.getenv("TEAMS_TENANT_ID") or extra.get("tenant_id", ""))
156+
extra.get("client_id") or _get_scoped_secret("TEAMS_CLIENT_ID", ""),
157+
extra.get("client_secret") or _get_scoped_secret("TEAMS_CLIENT_SECRET", ""),
158+
extra.get("tenant_id") or _get_scoped_secret("TEAMS_TENANT_ID", ""))
153159

154160

155161
def validate_config(config) -> bool:
@@ -164,19 +170,22 @@ def _env_enablement() -> dict | None:
164170
"""Seed ``PlatformConfig.extra`` from env before adapter construction so ``gateway status`` reflects
165171
env-only setups without the SDK. ``None`` when not minimally configured; ``home_channel`` becomes a
166172
``HomeChannel`` via the core hook."""
167-
client_id = os.getenv("TEAMS_CLIENT_ID", "").strip()
173+
# Every identity/endpoint here is per-profile (the app the secret belongs to, its regional
174+
# service URL, the cron home conversation): read them all through the profile scope so a
175+
# secondary is never seeded with the default profile's Teams app.
176+
client_id = _get_scoped_secret("TEAMS_CLIENT_ID", "").strip()
168177
client_secret = _get_scoped_secret("TEAMS_CLIENT_SECRET", "").strip()
169-
tenant_id = os.getenv("TEAMS_TENANT_ID", "").strip()
178+
tenant_id = _get_scoped_secret("TEAMS_TENANT_ID", "").strip()
170179
if not (client_id and client_secret and tenant_id):
171180
return None
172181
seed: dict = {"client_id": client_id, "client_secret": client_secret, "tenant_id": tenant_id}
173182
port = coerce_port(os.getenv("TEAMS_PORT", "").strip(), None)
174183
if port is not None:
175184
seed["port"] = port
176-
if service_url := os.getenv("TEAMS_SERVICE_URL", "").strip():
185+
if service_url := _get_scoped_secret("TEAMS_SERVICE_URL", "").strip():
177186
seed["service_url"] = service_url
178-
if home := os.getenv("TEAMS_HOME_CHANNEL", "").strip():
179-
seed["home_channel"] = {"chat_id": home, "name": os.getenv("TEAMS_HOME_CHANNEL_NAME", "Home")}
187+
if home := _get_scoped_secret("TEAMS_HOME_CHANNEL", "").strip():
188+
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("TEAMS_HOME_CHANNEL_NAME", "Home")}
180189
return seed
181190

182191

@@ -192,7 +201,7 @@ async def _standalone_send(
192201
client_id, client_secret, tenant_id = _credentials(pconfig)
193202
if not (client_id and client_secret and tenant_id):
194203
return {"error": "Teams standalone send: TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET, and TEAMS_TENANT_ID are all required"}
195-
raw_service_url = os.getenv("TEAMS_SERVICE_URL") or extra.get("service_url", "") or _DEFAULT_TEAMS_SERVICE_URL
204+
raw_service_url = extra.get("service_url") or _get_scoped_secret("TEAMS_SERVICE_URL", "") or _DEFAULT_TEAMS_SERVICE_URL
196205
service_url = _validate_teams_service_url(raw_service_url)
197206
for failed, error in (
198207
(service_url is None, f"TEAMS_SERVICE_URL host is not on the Bot Framework allowlist; "
@@ -339,9 +348,7 @@ class TeamsAdapter(BasePlatformAdapter):
339348
def __init__(self, config: PlatformConfig):
340349
super().__init__(config, Platform("teams"))
341350
extra = config.extra or {}
342-
self._client_id = extra.get("client_id") or os.getenv("TEAMS_CLIENT_ID", "")
343-
self._client_secret = extra.get("client_secret") or _get_scoped_secret("TEAMS_CLIENT_SECRET", "")
344-
self._tenant_id = extra.get("tenant_id") or os.getenv("TEAMS_TENANT_ID", "")
351+
self._client_id, self._client_secret, self._tenant_id = _credentials(config)
345352
# (token, expiry monotonic ts) for connector attachment auth; refreshed under
346353
# _bf_token_lock so concurrent attachments can't stampede the STS.
347354
self._bf_token_cache: Optional[tuple] = None

‎plugins/platforms/telegram/adapter.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2949,7 +2949,14 @@ async def connect(self, *, is_reconnect: bool = False) -> bool:
29492949
self._register_handlers(self._app)
29502950
await self._initialize_app_with_retries(builder)
29512951
await self._app.start()
2952-
webhook_url = os.getenv("TELEGRAM_WEBHOOK_URL", "").strip()
2952+
# Profile-scoped like TELEGRAM_WEBHOOK_SECRET: under multiplex os.environ holds the DEFAULT
2953+
# profile's URL, and registering it on a secondary bot pushes that bot's updates to the
2954+
# default's listener (and stops polling for it).
2955+
from agent.secret_scope import UnscopedSecretError, get_secret
2956+
try:
2957+
webhook_url = (get_secret("TELEGRAM_WEBHOOK_URL") or "").strip()
2958+
except UnscopedSecretError:
2959+
webhook_url = os.getenv("TELEGRAM_WEBHOOK_URL", "").strip()
29532960
if webhook_url:
29542961
await self._start_webhook_mode(webhook_url, is_reconnect=is_reconnect)
29552962
else:
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
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

Comments
 (0)