Skip to content

The agent that grows with you

fix(gateway): secondary-profile adapters no longer send their credentials to the default profile's host/identity

Tekniume253ea023344
diff --git a/plugins/platforms/dingtalk/adapter.py b/plugins/platforms/dingtalk/adapter.py
index a8f8452b320..4d41cf79121 100644
--- a/plugins/platforms/dingtalk/adapter.py
+++ b/plugins/platforms/dingtalk/adapter.py
@@ -116,7 +116,10 @@ def ensure_dingtalk_deps() -> bool:
def _credentials(extra: Optional[dict]) -> tuple:
"""(client_id, client_secret) from PlatformConfig.extra first, then env / scoped secret."""
extra = extra or {}
- return (extra.get("client_id") or os.getenv("DINGTALK_CLIENT_ID", ""), extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
+ # client_id goes through the same scoped reader as the secret: os.environ holds the DEFAULT
+ # profile's app id under multiplex, and pairing it with a secondary's secret authenticates as the wrong app.
+ return (extra.get("client_id") or _get_scoped_secret("DINGTALK_CLIENT_ID", ""),
+ extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
def check_dingtalk_requirements() -> bool:
@@ -627,7 +630,9 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
import httpx
except ImportError:
return {"error": "httpx not installed"}
- webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or os.getenv("DINGTALK_WEBHOOK_URL", "")
+ # Scoped: the webhook URL carries the robot's access_token and IS the delivery target — a raw
+ # environ read would post a secondary profile's cron output to the default profile's robot.
+ webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or _get_scoped_secret("DINGTALK_WEBHOOK_URL", "")
if not webhook_url:
return {"error": "DingTalk not configured. Set DINGTALK_WEBHOOK_URL env var or webhook_url in dingtalk platform extra config."}
try:
diff --git a/plugins/platforms/homeassistant/adapter.py b/plugins/platforms/homeassistant/adapter.py
index f1acc42329a..69608b399c9 100644
--- a/plugins/platforms/homeassistant/adapter.py
+++ b/plugins/platforms/homeassistant/adapter.py
@@ -77,7 +77,9 @@ class HomeAssistantAdapter(BasePlatformAdapter):
self._listen_task: Optional[asyncio.Task] = None
self._msg_id: int = 0
extra = config.extra or {}
- self._hass_url: str = (extra.get("url") or os.getenv("HASS_URL", "http://homeassistant.local:8123")).rstrip("/")
+ # URL is scoped like the token below: a secondary's HASS_TOKEN must never be posted to the
+ # DEFAULT profile's HA instance (os.environ under multiplex).
+ self._hass_url: str = (extra.get("url") or _get_scoped_secret("HASS_URL", "http://homeassistant.local:8123")).rstrip("/")
self._hass_token: str = config.token or _get_scoped_secret("HASS_TOKEN", "")
self._watch_domains: Set[str] = set(extra.get("watch_domains", []))
self._watch_entities: Set[str] = set(extra.get("watch_entities", []))
@@ -317,7 +319,7 @@ async def _standalone_send(
if not AIOHTTP_AVAILABLE:
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
extra = getattr(pconfig, "extra", {}) or {}
- hass_url = (extra.get("url") or os.getenv("HASS_URL", "")).rstrip("/")
+ hass_url = (extra.get("url") or _get_scoped_secret("HASS_URL", "")).rstrip("/")
token = (getattr(pconfig, "token", None) or _get_scoped_secret("HASS_TOKEN", "")).strip()
if not hass_url or not token:
return {"error": "Home Assistant standalone send: HASS_URL and HASS_TOKEN must both be set"}
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index 9b3f5ff8b18..707d4035e42 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -815,13 +815,17 @@ class MatrixAdapter(BasePlatformAdapter):
self.MAX_MESSAGE_LENGTH = self.max_message_length # mirrors other adapters for tooling
# A chunk near the outbound limit almost certainly has a continuation.
self._split_threshold = max(100, self.max_message_length - 100)
- self._homeserver: str = (config.extra.get("homeserver", "") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/")
+ # Homeserver/user_id/device_id go through the same scoped reader as the token/password:
+ # under multiplex os.environ holds the DEFAULT profile's identity, and pairing it with a
+ # secondary's credential sends that credential to the wrong homeserver (or reuses the
+ # default's E2EE device id).
+ self._homeserver: str = (config.extra.get("homeserver", "") or _startup_env_secret("MATRIX_HOMESERVER")).rstrip("/")
self._access_token: str = config.token or _startup_env_secret("MATRIX_ACCESS_TOKEN")
- self._user_id: str = config.extra.get("user_id", "") or os.getenv("MATRIX_USER_ID", "")
+ self._user_id: str = config.extra.get("user_id", "") or _startup_env_secret("MATRIX_USER_ID")
self._password: str = config.extra.get("password", "") or _startup_env_secret("MATRIX_PASSWORD")
self._e2ee_mode: str = _resolve_e2ee_mode(config.extra)
self._encryption: bool = self._e2ee_mode != "off"
- self._device_id: str = config.extra.get("device_id", "") or os.getenv("MATRIX_DEVICE_ID", "")
+ self._device_id: str = config.extra.get("device_id", "") or _startup_env_secret("MATRIX_DEVICE_ID")
self._device_id_unverified: bool = False
self._client: Any = None # mautrix.client.Client
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
except ImportError:
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
try:
- homeserver = (extra.get("homeserver") or os.getenv("MATRIX_HOMESERVER", "")).rstrip("/")
- # In-turn read inside an installed secret scope: honor get_secret, no env fallback.
+ # In-turn reads inside an installed secret scope: honor get_secret, no env fallback — for the
+ # homeserver too, so the scoped token is never sent to the default profile's server.
+ homeserver = (extra.get("homeserver") or get_secret("MATRIX_HOMESERVER", "") or "").rstrip("/")
token = getattr(pconfig, "token", None) or get_secret("MATRIX_ACCESS_TOKEN", "") or ""
if not homeserver or not token:
return {"error": "Matrix not configured (MATRIX_HOMESERVER, MATRIX_ACCESS_TOKEN required)"}
diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.py
index 41b441df301..fad47e449c2 100644
--- a/plugins/platforms/teams/adapter.py
+++ b/plugins/platforms/teams/adapter.py
@@ -144,12 +144,18 @@ def check_requirements() -> bool:
def _credentials(config) -> tuple[str, str, str]:
- """(client_id, client_secret, tenant_id): env first, then ``config.extra``."""
+ """(client_id, client_secret, tenant_id): ``config.extra`` first, then the profile-scoped env.
+
+ client_id/tenant_id are read through the same scoped reader as the secret: under multiplex,
+ ``os.environ`` holds the DEFAULT profile's app identity, and pairing it with a secondary's
+ secret requests a Bot Framework token for the wrong app. ``extra`` wins so a per-profile
+ config.yaml identity is never overridden by the process env.
+ """
extra = getattr(config, "extra", {}) or {}
return (
- os.getenv("TEAMS_CLIENT_ID") or extra.get("client_id", ""),
- _get_scoped_secret("TEAMS_CLIENT_SECRET") or extra.get("client_secret", ""),
- os.getenv("TEAMS_TENANT_ID") or extra.get("tenant_id", ""))
+ extra.get("client_id") or _get_scoped_secret("TEAMS_CLIENT_ID", ""),
+ extra.get("client_secret") or _get_scoped_secret("TEAMS_CLIENT_SECRET", ""),
+ extra.get("tenant_id") or _get_scoped_secret("TEAMS_TENANT_ID", ""))
def validate_config(config) -> bool:
@@ -164,19 +170,22 @@ def _env_enablement() -> dict | None:
"""Seed ``PlatformConfig.extra`` from env before adapter construction so ``gateway status`` reflects
env-only setups without the SDK. ``None`` when not minimally configured; ``home_channel`` becomes a
``HomeChannel`` via the core hook."""
- client_id = os.getenv("TEAMS_CLIENT_ID", "").strip()
+ # Every identity/endpoint here is per-profile (the app the secret belongs to, its regional
+ # service URL, the cron home conversation): read them all through the profile scope so a
+ # secondary is never seeded with the default profile's Teams app.
+ client_id = _get_scoped_secret("TEAMS_CLIENT_ID", "").strip()
client_secret = _get_scoped_secret("TEAMS_CLIENT_SECRET", "").strip()
- tenant_id = os.getenv("TEAMS_TENANT_ID", "").strip()
+ tenant_id = _get_scoped_secret("TEAMS_TENANT_ID", "").strip()
if not (client_id and client_secret and tenant_id):
return None
seed: dict = {"client_id": client_id, "client_secret": client_secret, "tenant_id": tenant_id}
port = coerce_port(os.getenv("TEAMS_PORT", "").strip(), None)
if port is not None:
seed["port"] = port
- if service_url := os.getenv("TEAMS_SERVICE_URL", "").strip():
+ if service_url := _get_scoped_secret("TEAMS_SERVICE_URL", "").strip():
seed["service_url"] = service_url
- if home := os.getenv("TEAMS_HOME_CHANNEL", "").strip():
- seed["home_channel"] = {"chat_id": home, "name": os.getenv("TEAMS_HOME_CHANNEL_NAME", "Home")}
+ if home := _get_scoped_secret("TEAMS_HOME_CHANNEL", "").strip():
+ seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("TEAMS_HOME_CHANNEL_NAME", "Home")}
return seed
@@ -192,7 +201,7 @@ async def _standalone_send(
client_id, client_secret, tenant_id = _credentials(pconfig)
if not (client_id and client_secret and tenant_id):
return {"error": "Teams standalone send: TEAMS_CLIENT_ID, TEAMS_CLIENT_SECRET, and TEAMS_TENANT_ID are all required"}
- raw_service_url = os.getenv("TEAMS_SERVICE_URL") or extra.get("service_url", "") or _DEFAULT_TEAMS_SERVICE_URL
+ raw_service_url = extra.get("service_url") or _get_scoped_secret("TEAMS_SERVICE_URL", "") or _DEFAULT_TEAMS_SERVICE_URL
service_url = _validate_teams_service_url(raw_service_url)
for failed, error in (
(service_url is None, f"TEAMS_SERVICE_URL host is not on the Bot Framework allowlist; "
@@ -339,9 +348,7 @@ class TeamsAdapter(BasePlatformAdapter):
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform("teams"))
extra = config.extra or {}
- self._client_id = extra.get("client_id") or os.getenv("TEAMS_CLIENT_ID", "")
- self._client_secret = extra.get("client_secret") or _get_scoped_secret("TEAMS_CLIENT_SECRET", "")
- self._tenant_id = extra.get("tenant_id") or os.getenv("TEAMS_TENANT_ID", "")
+ self._client_id, self._client_secret, self._tenant_id = _credentials(config)
# (token, expiry monotonic ts) for connector attachment auth; refreshed under
# _bf_token_lock so concurrent attachments can't stampede the STS.
self._bf_token_cache: Optional[tuple] = None
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index e1a9fef9780..986465ea57e 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -2949,7 +2949,14 @@ class TelegramAdapter(BasePlatformAdapter):
self._register_handlers(self._app)
await self._initialize_app_with_retries(builder)
await self._app.start()
- webhook_url = os.getenv("TELEGRAM_WEBHOOK_URL", "").strip()
+ # Profile-scoped like TELEGRAM_WEBHOOK_SECRET: under multiplex os.environ holds the DEFAULT
+ # profile's URL, and registering it on a secondary bot pushes that bot's updates to the
+ # default's listener (and stops polling for it).
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
+ webhook_url = (get_secret("TELEGRAM_WEBHOOK_URL") or "").strip()
+ except UnscopedSecretError:
+ webhook_url = os.getenv("TELEGRAM_WEBHOOK_URL", "").strip()
if webhook_url:
await self._start_webhook_mode(webhook_url, is_reconnect=is_reconnect)
else:
diff --git a/tests/gateway/test_multiplex_endpoint_identity_scope.py b/tests/gateway/test_multiplex_endpoint_identity_scope.py
new file mode 100644
index 00000000000..84b46984f52
--- /dev/null
+++ b/tests/gateway/test_multiplex_endpoint_identity_scope.py
@@ -0,0 +1,191 @@
+"""Invariant: an adapter's endpoint/identity resolves through the SAME profile scope as its secret.
+
+Under ``gateway.multiplex_profiles`` ``os.environ`` holds the DEFAULT profile's values; a secondary
+profile's ``.env`` exists only in its secret scope. Every adapter here already read its *secret*
+scope-aware but read the paired homeserver / URL / client_id / from-number / webhook URL raw from
+``os.environ`` — so the secondary's credential was sent to the default profile's host or identity.
+"""
+
+from __future__ import annotations
+
+import os
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from agent import secret_scope as ss
+from gateway.config import PlatformConfig
+from tests.gateway._plugin_adapter_loader import load_plugin_adapter
+
+DEFAULT_ENV = {
+ "MATRIX_HOMESERVER": "https://default.matrix.example", "MATRIX_USER_ID": "@default:example",
+ "MATRIX_DEVICE_ID": "DEFAULTDEV", "MATRIX_ACCESS_TOKEN": "default-matrix-token",
+ "HASS_URL": "http://default-ha.example:8123", "HASS_TOKEN": "default-ha-token",
+ "TEAMS_CLIENT_ID": "default-client-id", "TEAMS_TENANT_ID": "default-tenant",
+ "TEAMS_CLIENT_SECRET": "default-teams-secret", "TEAMS_HOME_CHANNEL": "default-conv",
+ "DINGTALK_CLIENT_ID": "default-ding-id", "DINGTALK_CLIENT_SECRET": "default-ding-secret",
+ "DINGTALK_WEBHOOK_URL": "https://oapi.dingtalk.com/robot/send?access_token=DEFAULT",
+ "TELEGRAM_WEBHOOK_URL": "https://default.example/tg",
+}
+SECONDARY = {
+ "MATRIX_HOMESERVER": "https://bot2.matrix.example", "MATRIX_USER_ID": "@bot2:example",
+ "MATRIX_DEVICE_ID": "BOT2DEV", "MATRIX_ACCESS_TOKEN": "bot2-matrix-token",
+ "HASS_URL": "http://bot2-ha.example:8123", "HASS_TOKEN": "bot2-ha-token",
+ "TEAMS_CLIENT_ID": "bot2-client-id", "TEAMS_TENANT_ID": "bot2-tenant",
+ "TEAMS_CLIENT_SECRET": "bot2-teams-secret", "TEAMS_HOME_CHANNEL": "bot2-conv",
+ "DINGTALK_CLIENT_ID": "bot2-ding-id", "DINGTALK_CLIENT_SECRET": "bot2-ding-secret",
+ "DINGTALK_WEBHOOK_URL": "https://oapi.dingtalk.com/robot/send?access_token=BOT2",
+ "TELEGRAM_WEBHOOK_URL": "https://bot2.example/tg",
+}
+
+
+def secondary_scope(monkeypatch):
+ """Default profile in os.environ, multiplex on, secondary profile's scope installed."""
+ for key, value in DEFAULT_ENV.items():
+ monkeypatch.setenv(key, value)
+ ss.set_multiplex_active(True)
+ token = ss.set_secret_scope(SECONDARY)
+ yield
+ ss.reset_secret_scope(token)
+ ss.set_multiplex_active(False)
+
+
+def test_matrix_homeserver_identity_follow_the_scoped_token(secondary_scope):
+ from plugins.platforms.matrix.adapter import MatrixAdapter
+
+ adapter = MatrixAdapter(PlatformConfig(enabled=True))
+ assert adapter._access_token == SECONDARY["MATRIX_ACCESS_TOKEN"]
+ assert (adapter._homeserver, adapter._user_id, adapter._device_id) == (
+ SECONDARY["MATRIX_HOMESERVER"], SECONDARY["MATRIX_USER_ID"], SECONDARY["MATRIX_DEVICE_ID"])
+
+
+async def test_matrix_standalone_send_posts_scoped_token_to_scoped_homeserver(secondary_scope, monkeypatch):
+ import aiohttp
+ from plugins.platforms.matrix import adapter as mx
+
+ seen = {}
+
+ class _Resp:
+ status = 200
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ async def json(self): return {"event_id": "$x"}
+ async def text(self): return ""
+
+ class _Sess:
+ def __init__(self, *a, **k): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ def put(self, url, **kw): seen["url"] = url; seen["headers"] = kw.get("headers", {}); return _Resp()
+
+ monkeypatch.setattr(aiohttp, "ClientSession", _Sess)
+ await mx._standalone_send(PlatformConfig(enabled=True), "!room:example", "hi")
+ assert seen["url"].startswith(SECONDARY["MATRIX_HOMESERVER"] + "/")
+ assert DEFAULT_ENV["MATRIX_HOMESERVER"] not in seen["url"]
+
+
+def test_homeassistant_url_follows_the_scoped_token(secondary_scope):
+ from plugins.platforms.homeassistant.adapter import HomeAssistantAdapter
+
+ adapter = HomeAssistantAdapter(PlatformConfig(enabled=True))
+ assert (adapter._hass_url, adapter._hass_token) == (SECONDARY["HASS_URL"], SECONDARY["HASS_TOKEN"])
+
+
+async def test_homeassistant_standalone_send_targets_scoped_url(secondary_scope, monkeypatch):
+ import aiohttp
+ from plugins.platforms.homeassistant import adapter as ha
+
+ seen = {}
+
+ class _Resp:
+ status = 200
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ async def text(self): return ""
+
+ class _Sess:
+ def __init__(self, *a, **k): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ def post(self, url, **kw): seen["url"] = url; return _Resp()
+
+ monkeypatch.setattr(aiohttp, "ClientSession", _Sess)
+ await ha._standalone_send(PlatformConfig(enabled=True), "x", "hi")
+ assert seen["url"].startswith(SECONDARY["HASS_URL"] + "/")
+
+
+def test_teams_credentials_pair_scoped_secret_with_scoped_app_identity(secondary_scope):
+ teams = load_plugin_adapter("teams")
+ assert teams._credentials(PlatformConfig(enabled=True)) == (
+ SECONDARY["TEAMS_CLIENT_ID"], SECONDARY["TEAMS_CLIENT_SECRET"], SECONDARY["TEAMS_TENANT_ID"])
+ # extra (per-profile config.yaml) must win over any env value.
+ assert teams._credentials(PlatformConfig(enabled=True, extra={"client_id": "yaml-id"}))[0] == "yaml-id"
+
+
+def test_teams_env_enablement_seeds_scoped_identity_and_home_channel(secondary_scope):
+ teams = load_plugin_adapter("teams")
+ seed = teams._env_enablement()
+ assert seed["client_id"] == SECONDARY["TEAMS_CLIENT_ID"]
+ assert seed["home_channel"]["chat_id"] == SECONDARY["TEAMS_HOME_CHANNEL"]
+
+
+def test_dingtalk_client_id_follows_the_scoped_secret(secondary_scope):
+ from plugins.platforms.dingtalk.adapter import _credentials
+
+ assert _credentials(None) == (SECONDARY["DINGTALK_CLIENT_ID"], SECONDARY["DINGTALK_CLIENT_SECRET"])
+
+
+async def test_dingtalk_standalone_send_posts_to_scoped_robot_webhook(secondary_scope, monkeypatch):
+ import httpx
+ from plugins.platforms.dingtalk import adapter as ding
+
+ posted = []
+
+ class _Resp:
+ def raise_for_status(self): pass
+ def json(self): return {"errcode": 0}
+
+ class _Client:
+ def __init__(self, *a, **k): pass
+ async def __aenter__(self): return self
+ async def __aexit__(self, *a): return False
+ async def post(self, url, **kw): posted.append(url); return _Resp()
+
+ monkeypatch.setattr(httpx, "AsyncClient", _Client)
+ result = await ding._standalone_send(PlatformConfig(enabled=True), "c", "hi")
+ assert result.get("success") is True
+ assert posted == [SECONDARY["DINGTALK_WEBHOOK_URL"]]
+
+
+async def test_telegram_connect_registers_scoped_webhook_url(secondary_scope, monkeypatch):
+ from plugins.platforms.telegram import adapter as tg
+
+ class _Builder:
+ def __getattr__(self, name):
+ return lambda *a, **k: self
+ def build(self):
+ app = MagicMock(); app.bot = MagicMock(); app.start = AsyncMock(); app.initialize = AsyncMock()
+ return app
+
+ monkeypatch.setattr(tg, "Application", type("_App", (), {"builder": staticmethod(_Builder)}))
+ adapter = tg.TelegramAdapter(PlatformConfig(enabled=True, token="bot2-token"))
+ for name in ("_wire_plugin_handlers", "_register_handlers", "_mark_connected", "_start_post_connect_housekeeping"):
+ monkeypatch.setattr(adapter, name, MagicMock())
+ monkeypatch.setattr(adapter, "_acquire_platform_lock", lambda *a, **k: True)
+ monkeypatch.setattr(adapter, "_build_ptb_requests", AsyncMock(return_value=(MagicMock(), MagicMock())))
+ monkeypatch.setattr(adapter, "_initialize_app_with_retries", AsyncMock())
+ seen = {}
+
+ async def _webhook(url, *, is_reconnect): seen["url"] = url
+ async def _polling(*, is_reconnect): seen["url"] = "<polling>"
+
+ monkeypatch.setattr(adapter, "_start_webhook_mode", _webhook)
+ monkeypatch.setattr(adapter, "_start_polling_mode", _polling)
+ assert await adapter.connect() is True
+ assert seen["url"] == SECONDARY["TELEGRAM_WEBHOOK_URL"]
+ assert os.environ["TELEGRAM_WEBHOOK_URL"] == DEFAULT_ENV["TELEGRAM_WEBHOOK_URL"] # env untouched; scope won