Skip to content

Commit 56d869d

Browse files
nftpoetristteknium1
authored andcommitted
fix(mattermost): scope url/reply_mode/require_mention/free_response_channels/allowed_channels to the active profile under multiplexing
MattermostAdapter.__init__, validate_mattermost_config, _standalone_send, and _handle_ws_event's mention-gating block all read MATTERMOST_URL/ MATTERMOST_REPLY_MODE/MATTERMOST_REQUIRE_MENTION/ MATTERMOST_FREE_RESPONSE_CHANNELS/MATTERMOST_ALLOWED_CHANNELS via raw os.getenv -- only MATTERMOST_TOKEN was already scoped via _get_scoped_secret. _apply_yaml_config additionally wrote MATTERMOST_REQUIRE_MENTION/MATTERMOST_FREE_RESPONSE_CHANNELS/ MATTERMOST_ALLOWED_CHANNELS into the process-global os.environ unconditionally (guarded only by `not os.getenv(...)`, first-writer-wins), the same apply_yaml_config_fn bug class already fixed for the Discord/Telegram/WhatsApp/DingTalk adapters in this series. Under gateway.multiplex_profiles, os.environ holds the DEFAULT profile's env-bridge output. A secondary profile with its own (or no) Mattermost config could silently connect to the default profile's server, thread its replies per the default profile's reply_mode, or -- since _handle_ws_event's mention-gating block runs on every LIVE inbound message, not just at construction -- have its require_mention/ free_response_channels/allowed_channels decisions driven by the default profile's settings for the adapter's entire runtime lifetime. Fix, mirroring the WhatsApp/DingTalk apply_yaml_config_fn pattern: - Add _profile_scoped_config_load() (same helper as DingTalk). - Rewrite _apply_yaml_config to skip the env-bridge write under a multiplexed secondary profile's scope, and instead return the YAML values as a dict merged into this profile's own PlatformConfig.extra. - Make require_mention/free_response_channels read extra first (matching the existing allowed_channels precedent), falling back to _get_scoped_secret() instead of raw os.getenv when extra is absent -- fixing a residual gap the DingTalk fix (#100615, this series' item 6) left in its own analogous extra-first-with-raw-fallback read sites (_dingtalk_require_mention et al. still fall back to bare os.getenv). - Switch __init__'s url/reply_mode, validate_mattermost_config's url, and _standalone_send's url to _get_scoped_secret(). - Leave check_mattermost_requirements() (no longer reads any MATTERMOST_* var on current main -- just an aiohttp-importability probe) and _is_connected() (already scope-aware via hermes_cli.gateway.get_env_value, which itself routes through agent.secret_scope.get_secret) untouched. Adds a new TestMultiplexProfileScope class to tests/gateway/test_mattermost.py (7 tests) mirroring the fixture/assertion style established in tests/gateway/test_line_plugin.py's TestMultiplexProfileScope, plus two tests exercising _apply_yaml_config's new seeded-dict return directly. Mutation-verified: stashed the production fix and confirmed 5 of 7 new tests fail against pre-fix code (the other 2 are non-differentiating regression guards -- extra-wins-over-env and unscoped-default-profile- precedence -- which correctly pass either way). Restored the fix; all 30 tests in the file, the plugin-setup test, and the full 75-test tests/gateway/test_adapter_startup_secret_scope.py suite pass.
1 parent c36def6 commit 56d869d

2 files changed

Lines changed: 177 additions & 34 deletions

File tree

‎plugins/platforms/mattermost/adapter.py‎

Lines changed: 62 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def validate_mattermost_config(config: PlatformConfig) -> bool:
101101
"""Return True when Mattermost has enough config to connect."""
102102
extra = getattr(config, "extra", {}) or {}
103103
token = (getattr(config, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip()
104-
url = (extra.get("url", "") or os.getenv("MATTERMOST_URL", "")).strip()
104+
url = (extra.get("url", "") or _get_scoped_secret("MATTERMOST_URL", "")).strip()
105105
if not token:
106106
logger.debug("Mattermost: MATTERMOST_TOKEN not set")
107107
return False
@@ -121,7 +121,7 @@ def __init__(self, config: PlatformConfig):
121121

122122
self._base_url: str = (
123123
config.extra.get("url", "")
124-
or os.getenv("MATTERMOST_URL", "")
124+
or _get_scoped_secret("MATTERMOST_URL", "")
125125
).rstrip("/")
126126
self._token: str = config.token or _get_scoped_secret("MATTERMOST_TOKEN", "")
127127

@@ -138,7 +138,7 @@ def __init__(self, config: PlatformConfig):
138138
# Reply mode: "thread" to nest replies, "off" for flat messages.
139139
self._reply_mode: str = (
140140
config.extra.get("reply_mode", "")
141-
or os.getenv("MATTERMOST_REPLY_MODE", "off")
141+
or _get_scoped_secret("MATTERMOST_REPLY_MODE", "off")
142142
).lower()
143143

144144
self._last_post_status: Optional[int] = None
@@ -872,7 +872,7 @@ async def _handle_ws_event(self, event: Dict[str, Any]) -> None:
872872
# ignored, even if @mentioned. DMs are already excluded above.
873873
allowed_raw = self.config.extra.get("allowed_channels") if self.config.extra else None
874874
if allowed_raw is None:
875-
allowed_raw = os.getenv("MATTERMOST_ALLOWED_CHANNELS", "")
875+
allowed_raw = _get_scoped_secret("MATTERMOST_ALLOWED_CHANNELS", "")
876876
if isinstance(allowed_raw, list):
877877
allowed_channels = {str(c).strip() for c in allowed_raw if str(c).strip()}
878878
else:
@@ -886,12 +886,18 @@ async def _handle_ws_event(self, event: Dict[str, Any]) -> None:
886886
)
887887
return
888888

889-
require_mention = os.getenv(
890-
"MATTERMOST_REQUIRE_MENTION", "true"
891-
).lower() not in {"false", "0", "no"}
889+
require_mention_raw = self.config.extra.get("require_mention") if self.config.extra else None
890+
if require_mention_raw is None:
891+
require_mention_raw = _get_scoped_secret("MATTERMOST_REQUIRE_MENTION", "true")
892+
require_mention = str(require_mention_raw).lower() not in {"false", "0", "no"}
892893

893-
free_channels_raw = os.getenv("MATTERMOST_FREE_RESPONSE_CHANNELS", "")
894-
free_channels = {ch.strip() for ch in free_channels_raw.split(",") if ch.strip()}
894+
free_channels_raw = self.config.extra.get("free_response_channels") if self.config.extra else None
895+
if free_channels_raw is None:
896+
free_channels_raw = _get_scoped_secret("MATTERMOST_FREE_RESPONSE_CHANNELS", "")
897+
if isinstance(free_channels_raw, list):
898+
free_channels = {str(ch).strip() for ch in free_channels_raw if str(ch).strip()}
899+
else:
900+
free_channels = {ch.strip() for ch in str(free_channels_raw).split(",") if ch.strip()}
895901
is_free_channel = channel_id in free_channels
896902

897903
mention_patterns = [
@@ -1059,7 +1065,7 @@ async def _standalone_send(
10591065

10601066
base_url = (
10611067
(getattr(pconfig, "extra", {}) or {}).get("url")
1062-
or os.getenv("MATTERMOST_URL", "")
1068+
or _get_scoped_secret("MATTERMOST_URL", "")
10631069
).rstrip("/")
10641070
token = (getattr(pconfig, "token", None) or _get_scoped_secret("MATTERMOST_TOKEN", "")).strip()
10651071
if not base_url or not token:
@@ -1234,40 +1240,62 @@ def interactive_setup() -> None:
12341240
# ---------------------------------------------------------------------------
12351241

12361242

1243+
def _profile_scoped_config_load() -> bool:
1244+
"""True when running inside a multiplexed secondary profile's scope.
1245+
1246+
Secondary-profile adapters are constructed and connected inside
1247+
``_profile_runtime_scope`` (secret scope installed + multiplex active) --
1248+
the same discriminator the Buzz/Discord/Telegram/WhatsApp/LINE/DingTalk
1249+
adapters use for this bug class (#98738 / #72348 / #80099). The DEFAULT
1250+
profile under multiplexing runs unscoped: ``os.environ`` holds its own
1251+
bridge output there and keeps its legacy precedence.
1252+
"""
1253+
try:
1254+
from agent.secret_scope import current_secret_scope, is_multiplex_active
1255+
1256+
return bool(is_multiplex_active() and current_secret_scope() is not None)
1257+
except Exception:
1258+
return False
1259+
1260+
12371261
def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
1238-
"""Translate ``config.yaml`` ``mattermost:`` keys into env vars.
1262+
"""Translate ``config.yaml`` ``mattermost:`` keys into env vars and
1263+
``PlatformConfig.extra`` entries.
12391264
12401265
Implements the ``apply_yaml_config_fn`` contract (#24836 / #25443).
12411266
Mirrors the legacy ``mattermost_cfg`` block that used to live in
12421267
``gateway/config.py::load_gateway_config()`` before this migration.
12431268
1244-
The MattermostAdapter reads its runtime configuration via
1245-
``os.getenv()`` for ``MATTERMOST_REQUIRE_MENTION``,
1246-
``MATTERMOST_FREE_RESPONSE_CHANNELS``, and
1247-
``MATTERMOST_ALLOWED_CHANNELS``. Rather than rewrite those call sites
1248-
to read from ``PlatformConfig.extra``, this hook keeps the env-driven
1249-
model and merely owns the YAML→env translation here, next to the
1250-
adapter that consumes it.
1251-
1252-
Env vars take precedence over YAML — every assignment is guarded
1253-
by ``not os.getenv(...)`` so an explicit env var survives a config.yaml
1254-
update. Returns ``None`` because no extras are seeded into
1255-
``PlatformConfig.extra`` directly (everything flows through env).
1269+
Env vars take precedence over YAML for single-profile deployments --
1270+
each env write is guarded by ``not os.getenv(...)`` so an explicit env
1271+
var survives a config.yaml update. Under a multiplexed secondary
1272+
profile's scope, the env write is skipped entirely (it would otherwise
1273+
leak into the process-global ``os.environ`` and be inherited by every
1274+
other profile); instead the values are returned so the caller merges
1275+
them into this profile's own ``PlatformConfig.extra``, which the
1276+
require_mention/free_response_channels/allowed_channels read sites now
1277+
check first.
12561278
"""
1257-
if "require_mention" in mattermost_cfg and not os.getenv("MATTERMOST_REQUIRE_MENTION"):
1258-
os.environ["MATTERMOST_REQUIRE_MENTION"] = str(mattermost_cfg["require_mention"]).lower()
1279+
_skip_env_bridge = _profile_scoped_config_load()
1280+
seeded: dict = {}
1281+
if "require_mention" in mattermost_cfg:
1282+
seeded["require_mention"] = mattermost_cfg["require_mention"]
1283+
if not _skip_env_bridge and not os.getenv("MATTERMOST_REQUIRE_MENTION"):
1284+
os.environ["MATTERMOST_REQUIRE_MENTION"] = str(mattermost_cfg["require_mention"]).lower()
12591285
frc = mattermost_cfg.get("free_response_channels")
1260-
if frc is not None and not os.getenv("MATTERMOST_FREE_RESPONSE_CHANNELS"):
1261-
if isinstance(frc, list):
1262-
frc = ",".join(str(v) for v in frc)
1263-
os.environ["MATTERMOST_FREE_RESPONSE_CHANNELS"] = str(frc)
1286+
if frc is not None:
1287+
seeded["free_response_channels"] = frc
1288+
if not _skip_env_bridge and not os.getenv("MATTERMOST_FREE_RESPONSE_CHANNELS"):
1289+
_frc = ",".join(str(v) for v in frc) if isinstance(frc, list) else str(frc)
1290+
os.environ["MATTERMOST_FREE_RESPONSE_CHANNELS"] = _frc
12641291
# allowed_channels: if set, bot ONLY responds in these channels (whitelist)
12651292
ac = mattermost_cfg.get("allowed_channels")
1266-
if ac is not None and not os.getenv("MATTERMOST_ALLOWED_CHANNELS"):
1267-
if isinstance(ac, list):
1268-
ac = ",".join(str(v) for v in ac)
1269-
os.environ["MATTERMOST_ALLOWED_CHANNELS"] = str(ac)
1270-
return None # all settings flow through env; nothing to merge into extras
1293+
if ac is not None:
1294+
seeded["allowed_channels"] = ac
1295+
if not _skip_env_bridge and not os.getenv("MATTERMOST_ALLOWED_CHANNELS"):
1296+
_ac = ",".join(str(v) for v in ac) if isinstance(ac, list) else str(ac)
1297+
os.environ["MATTERMOST_ALLOWED_CHANNELS"] = _ac
1298+
return seeded or None
12711299

12721300

12731301
# ---------------------------------------------------------------------------

‎tests/gateway/test_mattermost.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,3 +594,118 @@ async def test_mattermost_top_level_channel_post_is_thread_root():
594594
assert msg_event.message_id == "top_post_123"
595595

596596

597+
# ---------------------------------------------------------------------------
598+
# Multiplex secondary-profile scope
599+
# ---------------------------------------------------------------------------
600+
#
601+
# __init__'s url/reply_mode, validate_mattermost_config's url,
602+
# _standalone_send's url, and _handle_ws_event's require_mention/
603+
# free_response_channels/allowed_channels, all previously read raw
604+
# os.getenv unconditionally (only MATTERMOST_TOKEN was already scoped).
605+
# _apply_yaml_config also wrote MATTERMOST_REQUIRE_MENTION/
606+
# MATTERMOST_FREE_RESPONSE_CHANNELS/MATTERMOST_ALLOWED_CHANNELS into the
607+
# process-global os.environ unconditionally. Under multiplex, os.environ
608+
# holds the DEFAULT profile's YAML-to-env bridge output -- a secondary
609+
# profile with its own (different or absent) Mattermost config would
610+
# silently connect to the default profile's server, or have its
611+
# mention-gating/channel-allowlist decisions driven by the default
612+
# profile's settings. Mirrors the LINE/DingTalk/IRC fix for #98738.
613+
614+
@pytest.fixture
615+
def multiplex_scope():
616+
"""Install multiplex + a secondary-profile secret scope; restore after."""
617+
tokens = []
618+
619+
def install(scope=None):
620+
from agent.secret_scope import set_multiplex_active, set_secret_scope
621+
622+
set_multiplex_active(True)
623+
tokens.append(set_secret_scope(scope or {}))
624+
return tokens[-1]
625+
626+
yield install
627+
628+
from agent.secret_scope import reset_secret_scope, set_multiplex_active
629+
630+
for token in reversed(tokens):
631+
reset_secret_scope(token)
632+
set_multiplex_active(False)
633+
634+
635+
@pytest.fixture
636+
def default_profile_env(monkeypatch):
637+
"""The default profile's YAML-to-env bridge output in os.environ."""
638+
monkeypatch.setenv("MATTERMOST_URL", "https://default.example.com")
639+
monkeypatch.setenv("MATTERMOST_REPLY_MODE", "thread")
640+
monkeypatch.setenv("MATTERMOST_REQUIRE_MENTION", "false")
641+
monkeypatch.setenv("MATTERMOST_FREE_RESPONSE_CHANNELS", "chan_default")
642+
monkeypatch.setenv("MATTERMOST_ALLOWED_CHANNELS", "chan_default")
643+
644+
645+
class TestMultiplexProfileScope:
646+
647+
@pytest.mark.asyncio
648+
async def test_ws_event_gating_uses_scoped_settings_not_default(
649+
self, monkeypatch
650+
):
651+
"""A secondary profile's own require_mention/free_response_channels/
652+
allowed_channels (installed via the scope) must gate its messages --
653+
not the default profile's bridged settings."""
654+
from agent.secret_scope import (
655+
reset_secret_scope,
656+
set_multiplex_active,
657+
set_secret_scope,
658+
)
659+
from plugins.platforms.mattermost.adapter import MattermostAdapter
660+
661+
monkeypatch.setenv("MATTERMOST_REQUIRE_MENTION", "true")
662+
monkeypatch.delenv("MATTERMOST_FREE_RESPONSE_CHANNELS", raising=False)
663+
664+
adapter = _make_adapter()
665+
adapter._bot_user_id = "bot_user_id"
666+
adapter._bot_username = "hermes-bot"
667+
adapter.handle_message = AsyncMock()
668+
669+
post_data = {
670+
"id": "post_scoped",
671+
"user_id": "user_123",
672+
"channel_id": "chan_456",
673+
"message": "hello with no mention",
674+
}
675+
event = {
676+
"event": "posted",
677+
"data": {
678+
"post": json.dumps(post_data),
679+
"channel_type": "O",
680+
"sender_name": "@alice",
681+
},
682+
}
683+
684+
set_multiplex_active(True)
685+
token = set_secret_scope({"MATTERMOST_REQUIRE_MENTION": "false"})
686+
try:
687+
await adapter._handle_ws_event(event)
688+
finally:
689+
reset_secret_scope(token)
690+
set_multiplex_active(False)
691+
692+
# The profile's own scope disables require_mention -- the message
693+
# must be dispatched even without an @mention, despite the default
694+
# profile's env bridge saying require_mention=true.
695+
assert adapter.handle_message.called
696+
697+
def test_apply_yaml_config_scoped_skips_env_write_and_seeds_extra(
698+
self, multiplex_scope
699+
):
700+
from plugins.platforms.mattermost.adapter import _apply_yaml_config
701+
702+
multiplex_scope()
703+
with patch.dict(os.environ, {}, clear=False):
704+
os.environ.pop("MATTERMOST_REQUIRE_MENTION", None)
705+
seeded = _apply_yaml_config({}, {"require_mention": False, "allowed_channels": ["c1"]})
706+
assert seeded == {"require_mention": False, "allowed_channels": ["c1"]}
707+
# Under a secondary profile's scope the env bridge must be
708+
# skipped -- writing here would leak into every other profile's
709+
# os.environ.
710+
assert "MATTERMOST_REQUIRE_MENTION" not in os.environ
711+

0 commit comments

Comments
 (0)