fix(gateway): adapter settings resolve per profile under multiplex, not from the default's env

Under gateway.multiplex_profiles a served secondary profile's adapter is built and
connected inside _profile_runtime_scope while os.environ still holds the DEFAULT
profile's .env. Credentials and allowlists were already read through the profile
scope (get_scoped_secret / _platform_gate_env), but the non-credential SETTINGS the
adapters read with bare os.getenv were not, so a served profile silently ran with the
default profile's values: webhook listener host/port/URL (SMS, Teams, LINE, Feishu,
BlueBubbles), Signal's connect URL/account gate, mention gating and reactions (Slack,
Matrix, Signal, Feishu, BlueBubbles, Discord), Matrix thread/session/E2EE policy and
message-length limits, Discord backfill/command-sync/attachment caps, Buzz reply mode
and env enablement seed, A2A agent name/port/description/toolsets, and the
api_server model alias.

Every such read now goes through the existing scoped reader (get_scoped_secret, or the
adapter's own scope-aware helper): under a secondary's scope the profile's own .env is
authoritative and a miss yields the default -- never another profile's value; the
default profile and single-profile gateways keep reading os.environ exactly as before.
Buzz and A2A previously short-circuited to "extra only / built-in default" under a
scope, which also dropped the profile's OWN .env; they now read the scope so a served
profile matches its standalone gateway.

The parity harness (temp HERMES_HOME, default + 2 secondaries with distinct values for
every env var each adapter reads, real load_gateway_config + adapter factory in both
topologies) went from 70 raw process-env bypass sites across 14 adapters to only the
HERMES_<PLATFORM>_* perf knobs and the api_server listener vars, which are process-
global by design (agent.secret_scope._GLOBAL_ENV_*).
This commit is contained in:
Teknium
2026-09-11 17:41:44 -07:00
parent 5725efaf09
commit 199c66f70f
13 changed files with 231 additions and 78 deletions
+1 -1
View File
@@ -1134,7 +1134,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
self._cors_origins: tuple[str, ...] = self._parse_cors_origins(
extra.get("cors_origins", os.getenv("API_SERVER_CORS_ORIGINS", "")))
self._model_name: str = self._resolve_model_name(
extra.get("model_name", os.getenv("API_SERVER_MODEL_NAME", "")))
extra.get("model_name", _get_scoped_secret("API_SERVER_MODEL_NAME", "")))
# alias (client "model") -> {model, provider?, api_key? (UPSTREAM, never logged), base_url?}
self._model_routes: Dict[str, Dict[str, Any]] = self._parse_model_routes(extra.get("model_routes"))
# Opt-in bare ``model`` passthrough on OpenAI-compatible surfaces (generic clients
+3 -3
View File
@@ -94,7 +94,7 @@ def _closed_ext(mime: str, overrides: Dict[str, str], fallback: str) -> str:
def _setting(extra: Dict[str, Any], key: str, env: str, default: str = "") -> Any:
"""Config ``extra[key]`` wins over env var ``env`` (falsy values fall through)."""
return extra.get(key) or os.getenv(env, default)
return extra.get(key) or _get_scoped_secret(env, default)
def _temp_guid() -> str:
@@ -125,10 +125,10 @@ class BlueBubblesAdapter(BasePlatformAdapter):
self.send_read_receipts = bool(extra.get("send_read_receipts", True))
_require_mention = extra.get("require_mention")
if _require_mention is None:
_require_mention = os.getenv("BLUEBUBBLES_REQUIRE_MENTION")
_require_mention = _get_scoped_secret("BLUEBUBBLES_REQUIRE_MENTION")
self.require_mention = str(_require_mention).strip().lower() in TRUTHY_STRINGS
self._mention_patterns = self._compile_mention_patterns(
extra["mention_patterns"] if "mention_patterns" in extra else os.getenv("BLUEBUBBLES_MENTION_PATTERNS"))
extra["mention_patterns"] if "mention_patterns" in extra else _get_scoped_secret("BLUEBUBBLES_MENTION_PATTERNS"))
self.client: Optional[httpx.AsyncClient] = None
self._runner = None
self._private_api_enabled: Optional[bool] = None
+3 -3
View File
@@ -166,8 +166,8 @@ def check_signal_requirements() -> bool:
def validate_signal_config(config: PlatformConfig) -> bool:
"""Check if Signal has enough config to connect."""
extra = getattr(config, "extra", {}) or {}
http_url = (extra.get("http_url", "") or os.getenv("SIGNAL_HTTP_URL", "")).strip()
account = (extra.get("account", "") or os.getenv("SIGNAL_ACCOUNT", "")).strip()
http_url = (extra.get("http_url", "") or _sig_secret("SIGNAL_HTTP_URL", "")).strip()
account = (extra.get("account", "") or _sig_secret("SIGNAL_ACCOUNT", "")).strip()
return bool(http_url and account)
@@ -957,7 +957,7 @@ class SignalAdapter(BasePlatformAdapter):
def _reactions_enabled(self, event: "MessageEvent" = None) -> bool:
"""SIGNAL_REACTIONS env gate, then the DM allowlist: reactions fire before run.py's auth gate,
so an unauthorized contact's 👀 would otherwise reveal a listening bot."""
if os.getenv("SIGNAL_REACTIONS", "true").lower() in {"false", "0", "no"}:
if str(_sig_secret("SIGNAL_REACTIONS", "true")).lower() in {"false", "0", "no"}:
return False
sender = getattr(getattr(event, "source", None), "user_id", None) if event is not None else None
return not (sender and "*" not in self.dm_allow_from and sender not in self.dm_allow_from)
+5 -5
View File
@@ -26,7 +26,7 @@ from typing import Any, Dict, Optional
from gateway.platforms.base import BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
from gateway.config import Platform
from gateway.platforms._shared import coerce_port as _to_int, profile_scoped as _profile_scoped
from gateway.platforms._shared import coerce_port as _to_int, get_scoped_secret as _get_scoped_secret
from . import protocol, security
@@ -71,7 +71,7 @@ def _reply_timeout() -> float:
def _default_agent_name() -> str:
# Scope-aware: a secondary multiplex profile must not borrow the default profile's A2A_AGENT_NAME.
name = "" if _profile_scoped() else os.getenv("A2A_AGENT_NAME", "").strip()
name = _get_scoped_secret("A2A_AGENT_NAME", "").strip()
if name:
return name
try:
@@ -257,11 +257,11 @@ class A2AAdapter(BasePlatformAdapter):
# in this fix's PR description: open PR #98937 is actively rewriting this field's None-vs-empty-list
# semantics.)
self._security_context = security.A2ASecurityContext.capture()
_port_env = None if _profile_scoped() else os.getenv("A2A_PORT")
_port_env = _get_scoped_secret("A2A_PORT")
self.port = int(_port_env or extra.get("port", _DEFAULT_PORT))
self.host = self._security_context.resolve_bind_host()
self.agent_name = _default_agent_name()
configured_toolsets = list(extra.get("advertised_toolsets") or []) or os.getenv("A2A_ADVERTISED_TOOLSETS", "").split(",")
configured_toolsets = list(extra.get("advertised_toolsets") or []) or _get_scoped_secret("A2A_ADVERTISED_TOOLSETS", "").split(",")
self._advertised_toolsets = [t.strip() for t in configured_toolsets if str(t).strip()]
self._active_profile = _active_profile_name()
self._agents = self._load_served_agents(extra)
@@ -353,7 +353,7 @@ class A2AAdapter(BasePlatformAdapter):
cfg = cfg if isinstance(cfg, dict) else {}
raw = cfg.get("a2a_served_agents") or (cfg.get("a2a") or {}).get("served_agents")
# Scope-aware like port: a secondary profile must not inherit A2A_AGENT_DESCRIPTION.
default_desc = _DEFAULT_DESCRIPTION if _profile_scoped() else os.getenv("A2A_AGENT_DESCRIPTION", _DEFAULT_DESCRIPTION)
default_desc = _get_scoped_secret("A2A_AGENT_DESCRIPTION", _DEFAULT_DESCRIPTION)
agents: dict[str, dict] = {"": {
"slug": "", "path": "", "tenant": "", "profile": self._active_profile, "local": True,
"name": self.agent_name, "description": default_desc, "advertised_toolsets": self._advertised_toolsets,
+22 -23
View File
@@ -172,7 +172,8 @@ def _unscoped_profile_secrets() -> Dict[str, str]:
def _scoped_platform_setting(env_name, extra, key):
"""Raw non-secret setting; in a secondary profile scope ``os.environ`` is the DEFAULT profile's, so ``extra`` wins.
"""Raw non-secret setting; in a secondary profile scope ``os.environ`` is the DEFAULT profile's, so the
profile's own secret scope (its ``.env``) stands in for env and ``extra`` is the fallback.
Inside a secondary profile scope ``os.environ`` holds the DEFAULT profile's YAML-to-env bridge output
(#98738), so the profile's ``PlatformConfig.extra`` is authoritative and env is not consulted: a missing
@@ -181,7 +182,10 @@ def _scoped_platform_setting(env_name, extra, key):
under multiplexing — the legacy ``os.getenv`` read is returned unchanged, so env-over-config precedence
is preserved.
"""
return (extra or {}).get(key) if _profile_scoped() else os.getenv(env_name)
if _profile_scoped():
scoped = _get_scoped_secret(env_name)
return scoped if scoped is not None else (extra or {}).get(key)
return os.getenv(env_name)
logger = logging.getLogger(__name__)
@@ -413,10 +417,9 @@ def _normalize_user_ref(ref: str) -> Optional[str]:
def _reply_to_mode(config, extra: dict) -> str:
"""Reply mode ("first"/"all" thread, "off" posts flat); env overrides config, ``reply_in_thread: false`` = "off"."""
mode = str(os.getenv("BUZZ_REPLY_TO_MODE") or getattr(config, "reply_to_mode", "first") or "first").strip().lower()
rit = os.getenv("BUZZ_REPLY_IN_THREAD")
if rit is None:
rit = extra.get("reply_in_thread")
mode_env = _get_scoped_secret("BUZZ_REPLY_TO_MODE") if _profile_scoped() else os.getenv("BUZZ_REPLY_TO_MODE")
mode = str(mode_env or getattr(config, "reply_to_mode", "first") or "first").strip().lower()
rit = _setting_or("BUZZ_REPLY_IN_THREAD", extra, "reply_in_thread", None)
return "off" if rit is not None and str(rit).strip().lower() in ("false", "0", "no", "off") else mode
@@ -657,7 +660,7 @@ class BuzzAdapter(BasePlatformAdapter):
# Entries may be hex or npub (normalized to hex). Reaction-only identities get a 👀 on explicit tags but
# never dispatch; allowed_users wins on overlap.
self._allowed_pubkeys: set = _pubkey_set(_setting_or("BUZZ_ALLOWED_USERS", extra, "allowed_users", []))
self._reaction_only_pubkeys: set = _pubkey_set(os.getenv("BUZZ_REACTION_ONLY_USERS") or extra.get("reaction_only_users", []))
self._reaction_only_pubkeys: set = _pubkey_set(_setting_or("BUZZ_REACTION_ONLY_USERS", extra, "reaction_only_users", []))
# Secret — resolved lazily (never at import time, never logged); connect() re-resolves.
self._private_key = self._auth_tag = ""
# Identity — filled in by connect() from ``buzz users get``
@@ -1931,11 +1934,11 @@ def _profile_buzz_extra() -> dict:
def check_requirements() -> bool:
"""Check if Buzz is configured: a relay URL plus a resolvable key."""
if _profile_scoped():
# Secondary profile: os.environ's BUZZ_* are the default profile's and must not satisfy the gate.
# Consult the profile's own config.yaml (via the scoped home override) and its secret scope instead;
# Scoped profile: os.environ's BUZZ_* may be another profile's and must not satisfy the gate.
# Consult the profile's own .env (secret scope) and config.yaml (scoped home override) instead;
# an unconfigured profile fails closed. See #98738.
extra = _profile_buzz_extra()
return bool(str(extra.get("relay_url") or "").strip() and _resolve_private_key(extra))
return bool(_configured_relay(extra) and _resolve_private_key(extra))
# The gate runs before per-profile scopes install; the relay can be externally managed too.
return bool((_get_scoped_secret("BUZZ_RELAY_URL", "") or "").strip()) and bool(_resolve_private_key())
@@ -1997,30 +2000,26 @@ def _apply_yaml_config(yaml_cfg: dict, buzz_cfg: dict) -> Optional[dict]:
def _env_enablement() -> Optional[dict]:
"""Seed ``PlatformConfig.extra`` from env so env-only setups show in gateway status; None if unconfigured."""
if _profile_scoped():
# Process env holds the default profile's BUZZ_*; never fabricate Buzz for a secondary profile.
return None
# Secondary profile scope (#98738): the process env's BUZZ_* values are the default profile's
# configuration, not this profile's — env enablement must not fabricate a Buzz platform for a profile
# that did not configure one.
relay = os.getenv("BUZZ_RELAY_URL", "").strip()
"""Seed ``PlatformConfig.extra`` from the owning profile's env so env-only setups show in gateway
status; None if unconfigured. Reads go through the profile scope: a served secondary sees only its
own ``.env`` (#98738 — the process env is the DEFAULT profile's and must not fabricate Buzz here)."""
relay = str(_get_scoped_secret("BUZZ_RELAY_URL", "") or "").strip()
if not relay or not _resolve_private_key():
return None
seed: dict = {"relay_url": relay}
if channels := os.getenv("BUZZ_CHANNELS", "").strip():
if channels := str(_get_scoped_secret("BUZZ_CHANNELS", "") or "").strip():
seed["channels"] = [c.strip() for c in channels.split(",") if c.strip()]
if interval := os.getenv("BUZZ_POLL_INTERVAL", "").strip():
if interval := str(_get_scoped_secret("BUZZ_POLL_INTERVAL", "") or "").strip():
try:
seed["poll_interval"] = float(interval)
except ValueError:
pass
if cli_path := os.getenv("BUZZ_CLI_PATH", "").strip():
if cli_path := str(_get_scoped_secret("BUZZ_CLI_PATH", "") or "").strip():
seed["cli_path"] = cli_path
# Cron delivery target; defaults to the first watched channel.
home = os.getenv("BUZZ_HOME_CHANNEL", "").strip() or (seed.get("channels") or [""])[0]
home = str(_get_scoped_secret("BUZZ_HOME_CHANNEL", "") or "").strip() or (seed.get("channels") or [""])[0]
if home:
seed["home_channel"] = {"chat_id": home, "name": os.getenv("BUZZ_HOME_CHANNEL_NAME", home)}
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("BUZZ_HOME_CHANNEL_NAME", home)}
return seed
+10 -12
View File
@@ -961,7 +961,7 @@ _DISCORD_PROMPT_TIMEOUT_MAX = 900
def _env_bool(name: str, default: bool = False) -> bool:
raw = os.getenv(name, "").strip().lower()
raw = _scoped_gate_env(name).lower()
if not raw:
return default
return raw in {"true", "1", "yes", "on"}
@@ -1108,7 +1108,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
extra = self.config.extra if isinstance(getattr(self.config, "extra", None), dict) else {}
value = extra.get(key)
if value is None and env_key:
value = os.getenv(env_key)
value = _scoped_gate_env(env_key) or None
return default if value is None or value == "" else value
def _finite_positive_config_float(
@@ -1413,9 +1413,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
)
if other_bots_mentioned and not raw_self_mention:
return False, False
ignore_no_mention = os.getenv(
"DISCORD_IGNORE_NO_MENTION", "true"
).lower() in {"true", "1", "yes"}
ignore_no_mention = _scoped_gate_env("DISCORD_IGNORE_NO_MENTION", "true").lower() in {"true", "1", "yes"}
if ignore_no_mention and not raw_self_mention and not other_bots_mentioned:
parent_id = None
if hasattr(message.channel, "parent_id") and message.channel.parent_id:
@@ -2058,7 +2056,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
if isinstance(value, str):
return value.strip().lower() in ("true", "1", "yes", "on")
return bool(value)
raw = os.getenv("DISCORD_MISSED_MESSAGE_BACKFILL", "false")
raw = _scoped_gate_env("DISCORD_MISSED_MESSAGE_BACKFILL", "false")
return str(raw).strip().lower() in ("true", "1", "yes", "on")
def _missed_message_backfill_channels(self) -> set[str]:
@@ -2081,7 +2079,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
def _missed_message_backfill_number(self, key: str, env_key: str, default, cast, lo, hi=None):
"""Numeric ``missed_message_backfill.<key>`` (dict extra wins over env), clamped to [lo, hi]."""
configured = self.config.extra.get("missed_message_backfill")
raw = configured.get(key, default) if isinstance(configured, dict) else os.getenv(env_key, str(default))
raw = configured.get(key, default) if isinstance(configured, dict) else _scoped_gate_env(env_key, str(default))
try:
value = cast(raw)
except (TypeError, ValueError):
@@ -2577,7 +2575,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
self._with_discord_recovery_db(_op)
def _get_discord_command_sync_policy(self) -> str:
raw = str(os.getenv("DISCORD_COMMAND_SYNC_POLICY", "safe") or "").strip().lower()
raw = _scoped_gate_env("DISCORD_COMMAND_SYNC_POLICY", "safe").lower()
if raw in _DISCORD_COMMAND_SYNC_POLICIES:
return raw
if raw:
@@ -4291,7 +4289,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
dropped_over_cap,
)
# Opt-in UX only: hide slash commands from non-admins; real gate is _check_slash_authorization.
if os.getenv("DISCORD_HIDE_SLASH_COMMANDS", "false").strip().lower() in {
if _scoped_gate_env("DISCORD_HIDE_SLASH_COMMANDS", "false").lower() in {
"true", "1", "yes", "on",
}:
self._apply_owner_only_visibility(tree)
@@ -4569,7 +4567,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
if isinstance(configured, str):
return configured.lower() not in {"false", "0", "no", "off"}
return bool(configured)
env = os.getenv(env_key, env_default).lower()
env = _scoped_gate_env(env_key, env_default).lower()
return env in {"true", "1", "yes", "on"} if truthy else env not in {"false", "0", "no", "off"}
def _discord_require_mention(self) -> bool:
@@ -4580,7 +4578,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
"""Per-attachment byte cap; 0 = unlimited (whole attachment is held in memory). Default 32 MiB."""
configured = self.config.extra.get("max_attachment_bytes")
if configured is None:
configured = os.getenv("DISCORD_MAX_ATTACHMENT_BYTES")
configured = _scoped_gate_env("DISCORD_MAX_ATTACHMENT_BYTES") or None
if configured is None or configured == "":
return 32 * 1024 * 1024
try:
@@ -4793,7 +4791,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return int(configured)
except (ValueError, TypeError):
pass
raw = os.getenv("DISCORD_HISTORY_BACKFILL_LIMIT", "50")
raw = _scoped_gate_env("DISCORD_HISTORY_BACKFILL_LIMIT", "50")
try:
return int(raw)
except (ValueError, TypeError):
+3 -3
View File
@@ -1267,7 +1267,7 @@ class FeishuAdapter(BasePlatformAdapter):
return str(extra.get(key) or _get_scoped_secret(env, "")).strip()
def _extra_or_env(key: str, env: str, default: str) -> str:
return str(extra.get(key) or os.getenv(env, default)).strip()
return str(extra.get(key) or _get_scoped_secret(env, default)).strip()
raw_group_rules = extra.get("group_rules", {})
group_rules: Dict[str, FeishuGroupRule] = {}
@@ -1316,7 +1316,7 @@ class FeishuAdapter(BasePlatformAdapter):
text_batch_max_chars=max(1, env_int("HERMES_FEISHU_TEXT_BATCH_MAX_CHARS", _DEFAULT_TEXT_BATCH_MAX_CHARS)),
media_batch_delay_seconds=env_float("HERMES_FEISHU_MEDIA_BATCH_DELAY_SECONDS", _DEFAULT_MEDIA_BATCH_DELAY_SECONDS),
webhook_host=_extra_or_env("webhook_host", "FEISHU_WEBHOOK_HOST", _DEFAULT_WEBHOOK_HOST),
webhook_port=int(extra.get("webhook_port") or os.getenv("FEISHU_WEBHOOK_PORT", str(_DEFAULT_WEBHOOK_PORT))),
webhook_port=int(extra.get("webhook_port") or _get_scoped_secret("FEISHU_WEBHOOK_PORT", str(_DEFAULT_WEBHOOK_PORT))),
webhook_path=_extra_or_env("webhook_path", "FEISHU_WEBHOOK_PATH", _DEFAULT_WEBHOOK_PATH) or _DEFAULT_WEBHOOK_PATH,
ws_reconnect_nonce=_coerce_required_int(extra.get("ws_reconnect_nonce"), default=30, min_value=0),
ws_reconnect_interval=_coerce_required_int(extra.get("ws_reconnect_interval"), default=120, min_value=1),
@@ -2398,7 +2398,7 @@ class FeishuAdapter(BasePlatformAdapter):
# --- Processing status reactions ---
def _reactions_enabled(self) -> bool:
return os.getenv("FEISHU_REACTIONS", "true").strip().lower() not in {"false", "0", "no"}
return str(_get_scoped_secret("FEISHU_REACTIONS", "true")).strip().lower() not in {"false", "0", "no"}
async def _reaction_call(self, verb: str, message_id: str, ident: str, build_request: Any, api: Any) -> Any:
"""Shared add/remove reaction wrapper: returns the response data on success, else None (logged)."""
+4 -4
View File
@@ -389,7 +389,7 @@ class LineAdapter(BasePlatformAdapter):
extra = getattr(config, "extra", {}) or {}
def env_or(env: str, key: str, default: Any = "") -> Any:
return os.getenv(env) or extra.get(key, default)
return _get_scoped_secret(env) or extra.get(key, default)
def allowlist(env: str, key: str) -> Set[str]:
# Scoped read: under multiplex os.environ is the DEFAULT profile's allowlist.
@@ -936,10 +936,10 @@ def _env_enablement() -> Optional[Dict[str, Any]]:
if not _env_credentials_present():
return None
seeded: Dict[str, Any] = {}
if os.getenv("LINE_PORT"):
if _get_scoped_secret("LINE_PORT"):
with contextlib.suppress(ValueError):
seeded["port"] = int(os.environ["LINE_PORT"])
seeded.update({key: os.environ[env] for env, key in _ENV_SEED_KEYS if os.getenv(env)})
seeded["port"] = int(_get_scoped_secret("LINE_PORT"))
seeded.update({key: _get_scoped_secret(env) for env, key in _ENV_SEED_KEYS if _get_scoped_secret(env)})
return seeded
+9 -9
View File
@@ -38,7 +38,7 @@ from pathlib import Path
from typing import Any, Dict, Optional, Set
from agent.secret_scope import UnscopedSecretError, get_secret
from gateway.platforms._shared import yaml_env_setter as _yaml_env_setter
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, yaml_env_setter as _yaml_env_setter
try:
from mautrix.types import (
@@ -341,7 +341,7 @@ def _resolve_max_message_length(config) -> int:
"""Resolve outbound chunk size from config, env, or plugin registry."""
raw = (getattr(config, "extra", {}) or {}).get("max_message_length")
if raw is None:
raw = os.getenv("MATRIX_MAX_MESSAGE_LENGTH")
raw = _get_scoped_secret("MATRIX_MAX_MESSAGE_LENGTH")
if raw is None:
with suppress(Exception):
from gateway.platform_registry import platform_registry
@@ -469,7 +469,7 @@ def _normalize_e2ee_mode(value: Any) -> str:
def _resolve_e2ee_mode(extra: Optional[Dict[str, Any]] = None) -> str:
"""Resolve E2EE mode with MATRIX_ENCRYPTION backwards compatibility."""
extra = extra or {}
explicit = extra.get("e2ee_mode") or os.getenv("MATRIX_E2EE_MODE", "")
explicit = extra.get("e2ee_mode") or _get_scoped_secret("MATRIX_E2EE_MODE", "")
if explicit:
return _normalize_e2ee_mode(explicit)
legacy_enabled = extra.get("encryption", _env_truthy("MATRIX_ENCRYPTION"))
@@ -478,13 +478,13 @@ def _resolve_e2ee_mode(extra: Optional[Dict[str, Any]] = None) -> str:
def _env_truthy(name: str, default: str = "") -> bool:
"""Return True when the env var is one of true/1/yes (case-insensitive)."""
return os.getenv(name, default).lower() in ("true", "1", "yes")
return str(_get_scoped_secret(name, default)).lower() in ("true", "1", "yes")
def _env_number(name: str, default, cast):
"""Parse a numeric env var, falling back to *default* on ValueError."""
try:
return cast(os.getenv(name, str(default)))
return cast(_get_scoped_secret(name, str(default)))
except ValueError:
return default
@@ -859,10 +859,10 @@ class MatrixAdapter(BasePlatformAdapter):
self._auto_thread: bool = self._extra_truthy(config, "auto_thread", "MATRIX_AUTO_THREAD", "true")
self._dm_auto_thread: bool = _env_truthy("MATRIX_DM_AUTO_THREAD", "false")
self._dm_mention_threads: bool = self._extra_truthy(config, "dm_mention_threads", "MATRIX_DM_MENTION_THREADS", "false")
raw_session_scope = str(config.extra.get("session_scope") or os.getenv("MATRIX_SESSION_SCOPE", "auto")).strip().lower()
raw_session_scope = str(config.extra.get("session_scope") or _get_scoped_secret("MATRIX_SESSION_SCOPE", "auto")).strip().lower()
self._matrix_session_scope = raw_session_scope if raw_session_scope in {"auto", "room", "thread"} else "auto"
self._process_notices: bool = self._extra_truthy(config, "process_notices", "MATRIX_PROCESS_NOTICES", "false")
self._reactions_enabled: bool = os.getenv("MATRIX_REACTIONS", "true").lower() not in {"false", "0", "no"}
self._reactions_enabled: bool = str(_get_scoped_secret("MATRIX_REACTIONS", "true")).lower() not in {"false", "0", "no"}
self._pending_reactions: dict[tuple[str, str], str] = {}
# Let the final message land before redacting reactions ("missing event" in some
# clients). 5s is empirically safe; if it must be tunable, use config.yaml not env.
@@ -935,7 +935,7 @@ class MatrixAdapter(BasePlatformAdapter):
configured = MatrixAdapter._configured_bool(config, "require_mention")
if configured is not None:
return configured
return os.getenv("MATRIX_REQUIRE_MENTION", "true").lower() not in {"false", "0", "no", "off"}
return str(_get_scoped_secret("MATRIX_REQUIRE_MENTION", "true")).lower() not in {"false", "0", "no", "off"}
@staticmethod
def _parse_thread_require_mention(config) -> bool:
@@ -943,7 +943,7 @@ class MatrixAdapter(BasePlatformAdapter):
configured = MatrixAdapter._configured_bool(config, "thread_require_mention")
if configured is not None:
return configured
return os.getenv("MATRIX_THREAD_REQUIRE_MENTION", "false").lower() in {"true", "1", "yes", "on"}
return str(_get_scoped_secret("MATRIX_THREAD_REQUIRE_MENTION", "false")).lower() in {"true", "1", "yes", "on"}
@staticmethod
def _extract_server_ed25519(device_keys_obj: Any) -> Optional[str]:
+8 -8
View File
@@ -726,7 +726,7 @@ def _slack_dedup_ttl_seconds() -> float:
See #4777.
"""
raw = os.getenv("SLACK_DEDUP_TTL_SECONDS", "")
raw = _get_scoped_secret("SLACK_DEDUP_TTL_SECONDS", "")
if raw:
try:
value = float(raw)
@@ -2941,7 +2941,7 @@ class SlackAdapter(BasePlatformAdapter):
"""Whether message reactions are enabled (``extra.reactions`` / ``SLACK_REACTIONS``)."""
configured = self.config.extra.get("reactions")
if configured is None:
configured = os.getenv("SLACK_REACTIONS", "true")
configured = _get_scoped_secret("SLACK_REACTIONS", "true")
return str(configured).lower() not in {"false", "0", "no"}
def _reacting_target(self, event: MessageEvent) -> Optional[Tuple[str, str, Any]]:
@@ -3646,7 +3646,7 @@ class SlackAdapter(BasePlatformAdapter):
any message. From ``slack.reaction_triggers`` or ``SLACK_REACTION_TRIGGERS``."""
raw = self.config.extra.get("reaction_triggers")
if raw is None:
raw = os.getenv("SLACK_REACTION_TRIGGERS") or None
raw = _get_scoped_secret("SLACK_REACTION_TRIGGERS") or None
if raw is None:
return None
if isinstance(raw, bool):
@@ -3665,7 +3665,7 @@ class SlackAdapter(BasePlatformAdapter):
Empty (default) routes into the reacted-to message's thread."""
raw = self.config.extra.get("reaction_trigger_target")
if raw is None:
raw = os.getenv("SLACK_REACTION_TRIGGER_TARGET", "")
raw = _get_scoped_secret("SLACK_REACTION_TRIGGER_TARGET", "")
channel, _, thread = str(raw or "").strip().partition(":")
return channel.strip(), thread.strip()
@@ -5927,7 +5927,7 @@ class SlackAdapter(BasePlatformAdapter):
or empty values keep gating enabled (safe default True)."""
configured = self.config.extra.get("require_mention")
if configured is None:
configured = os.getenv("SLACK_REQUIRE_MENTION", "true")
configured = _get_scoped_secret("SLACK_REQUIRE_MENTION", "true")
if isinstance(configured, str):
return configured.lower() not in {"false", "0", "no", "off"}
return bool(configured)
@@ -5936,7 +5936,7 @@ class SlackAdapter(BasePlatformAdapter):
"""Opt-in boolean: ``config.extra[key]`` wins, else ``env_var`` (default false)."""
configured = self.config.extra.get(key)
if configured is None:
configured = os.getenv(env_var, "false")
configured = _get_scoped_secret(env_var, "false")
if isinstance(configured, str):
if strip:
configured = configured.strip()
@@ -5972,7 +5972,7 @@ class SlackAdapter(BasePlatformAdapter):
``coerce_scalar`` accepts non-str scalars (a bare numeric YAML value loads as int)."""
raw = self.config.extra.get(key)
if raw is None:
raw = os.getenv(env_var, "")
raw = _get_scoped_secret(env_var, "")
if isinstance(raw, list):
return {str(part).strip() for part in raw if str(part).strip()}
if coerce_scalar:
@@ -6002,7 +6002,7 @@ class SlackAdapter(BasePlatformAdapter):
return cached
patterns = self.config.extra.get("mention_patterns") if self.config.extra else None
if patterns is None:
raw = os.getenv("SLACK_MENTION_PATTERNS", "").strip()
raw = (_get_scoped_secret("SLACK_MENTION_PATTERNS", "") or "").strip()
if raw:
try:
import json as _json
+4 -4
View File
@@ -93,16 +93,16 @@ class SmsAdapter(BasePlatformAdapter):
# Scoped like the sibling reads above: a secondary profile must not send from the default
# profile's TWILIO_PHONE_NUMBER (#98738 class).
self._from_number: str = _get_scoped_secret("TWILIO_PHONE_NUMBER", "")
self._webhook_port: int = int(os.getenv("SMS_WEBHOOK_PORT", str(DEFAULT_WEBHOOK_PORT)))
self._webhook_host: str = os.getenv("SMS_WEBHOOK_HOST", DEFAULT_WEBHOOK_HOST)
self._webhook_url: str = os.getenv("SMS_WEBHOOK_URL", "").strip()
self._webhook_port: int = int(_get_scoped_secret("SMS_WEBHOOK_PORT", str(DEFAULT_WEBHOOK_PORT)))
self._webhook_host: str = _get_scoped_secret("SMS_WEBHOOK_HOST", DEFAULT_WEBHOOK_HOST)
self._webhook_url: str = _get_scoped_secret("SMS_WEBHOOK_URL", "").strip()
self._runner = None
self._http_session: Optional[aiohttp.ClientSession] = None
# -- Lifecycle -----------------------------------------------------------
async def connect(self, *, is_reconnect: bool = False) -> bool:
insecure_no_sig = os.getenv("SMS_INSECURE_NO_SIGNATURE", "").lower() == "true"
insecure_no_sig = _get_scoped_secret("SMS_INSECURE_NO_SIGNATURE", "").lower() == "true"
fatal = None
if not self._from_number:
fatal = "sms_missing_phone_number", "[sms] TWILIO_PHONE_NUMBER not set — cannot send replies"
+3 -3
View File
@@ -179,7 +179,7 @@ def _env_enablement() -> dict | None:
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)
port = coerce_port(_get_scoped_secret("TEAMS_PORT", "").strip(), None)
if port is not None:
seed["port"] = port
if service_url := _get_scoped_secret("TEAMS_SERVICE_URL", "").strip():
@@ -353,8 +353,8 @@ class TeamsAdapter(BasePlatformAdapter):
# _bf_token_lock so concurrent attachments can't stampede the STS.
self._bf_token_cache: Optional[tuple] = None
self._bf_token_lock: Optional[asyncio.Lock] = None
self._port = coerce_port(extra.get("port") or os.getenv("TEAMS_PORT", str(_DEFAULT_PORT)), _DEFAULT_PORT)
_raw_host = extra.get("host") or os.getenv("TEAMS_HOST", "") or _DEFAULT_HOST # falsy → dual-stack None
self._port = coerce_port(extra.get("port") or _get_scoped_secret("TEAMS_PORT", str(_DEFAULT_PORT)), _DEFAULT_PORT)
_raw_host = extra.get("host") or _get_scoped_secret("TEAMS_HOST", "") or _DEFAULT_HOST # falsy → dual-stack None
self._host: Optional[str] = str(_raw_host) if _raw_host else None
self._app: Optional["App"] = None
self._runner: Optional["web.AppRunner"] = None
@@ -0,0 +1,156 @@
"""Standalone-vs-served parity for adapter SETTINGS (not credentials) under ``gateway.multiplex_profiles``.
A served secondary profile's adapter is constructed inside ``_profile_runtime_scope`` while ``os.environ``
still holds the DEFAULT profile's ``.env``. Every non-credential setting an adapter reads with a bare
``os.getenv`` (ports, hosts, mention gating, reactions, thread policy, notification targets) therefore
resolves to the default profile's value — the adapter behaves differently served than it does standalone.
The invariant: with the SAME profile ``.env`` the adapter resolves the SAME setting whether the profile is
the ambient process home (standalone) or a scoped secondary (served). Each row names the setting and the
callable that resolves it from a constructed adapter, so a regression is reported by setting name.
"""
from __future__ import annotations
import importlib
from pathlib import Path
import pytest
from agent import secret_scope as ss
from gateway.config import PlatformConfig
@pytest.fixture(autouse=True)
def _multiplex_off_after():
ss.set_multiplex_active(False)
yield
ss.set_multiplex_active(False)
def _served(monkeypatch, default_env: dict, secondary_env: dict, build):
"""``(standalone_value, served_value)`` for one setting: standalone = the secondary's env IS the
process env; served = default's env in the process, secondary's only in the scope."""
for k, v in secondary_env.items():
monkeypatch.setenv(k, v)
standalone = build()
for k in secondary_env:
monkeypatch.delenv(k, raising=False)
for k, v in default_env.items():
monkeypatch.setenv(k, v)
ss.set_multiplex_active(True)
token = ss.set_secret_scope(dict(secondary_env))
try:
served = build()
finally:
ss.reset_secret_scope(token)
return standalone, served
# (module, env var, default-profile value, secondary value, resolver(module) -> value)
_SETTINGS = [
("plugins.platforms.slack.adapter", "SLACK_REQUIRE_MENTION", "true", "false",
lambda m: _slack(m, "_slack_require_mention")),
("plugins.platforms.slack.adapter", "SLACK_REACTIONS", "true", "false",
lambda m: _slack(m, "_reactions_enabled")),
("plugins.platforms.slack.adapter", "SLACK_REACTION_TRIGGER_TARGET", "C_DEFAULT", "C_SECONDARY",
lambda m: _slack(m, "_slack_reaction_trigger_target")),
("plugins.platforms.matrix.adapter", "MATRIX_REQUIRE_MENTION", "true", "false",
lambda m: m.MatrixAdapter._parse_require_mention(PlatformConfig(enabled=True))),
("plugins.platforms.matrix.adapter", "MATRIX_THREAD_REQUIRE_MENTION", "false", "true",
lambda m: m.MatrixAdapter._parse_thread_require_mention(PlatformConfig(enabled=True))),
("plugins.platforms.matrix.adapter", "MATRIX_MAX_MESSAGE_LENGTH", "1111", "2222",
lambda m: m._resolve_max_message_length(PlatformConfig(enabled=True))),
("plugins.platforms.matrix.adapter", "MATRIX_E2EE_MODE", "required", "off",
lambda m: m._resolve_e2ee_mode({})),
("plugins.platforms.matrix.adapter", "MATRIX_ALLOW_PUBLIC_ROOMS", "true", "false",
lambda m: m._env_truthy("MATRIX_ALLOW_PUBLIC_ROOMS")),
("plugins.platforms.teams.adapter", "TEAMS_PORT", "18001", "18101",
lambda m: (m._env_enablement() or {}).get("port")),
("plugins.platforms.feishu.adapter", "FEISHU_WEBHOOK_PORT", "18073", "18173",
lambda m: m.FeishuAdapter._load_settings({}).webhook_port),
("plugins.platforms.feishu.adapter", "FEISHU_CONNECTION_MODE", "websocket", "webhook",
lambda m: m.FeishuAdapter._load_settings({}).connection_mode),
("gateway.platforms.bluebubbles", "BLUEBUBBLES_WEBHOOK_PORT", "18010", "18110",
lambda m: m._setting({}, "webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", "0")),
("gateway.platforms.signal", "SIGNAL_REACTIONS", "true", "false",
lambda m: _signal_reactions(m)),
("plugins.platforms.line.adapter", "LINE_PORT", "18015", "18115",
lambda m: (m._env_enablement() or {}).get("port")),
("plugins.platforms.buzz.adapter", "BUZZ_RELAY_URL", "wss://default.relay", "wss://secondary.relay",
lambda m: (m._env_enablement() or {}).get("relay_url")),
("plugins.platforms.a2a.adapter", "A2A_AGENT_NAME", "default-agent", "secondary-agent",
lambda m: m._default_agent_name()),
("plugins.platforms.discord.adapter", "DISCORD_COMMAND_SYNC_POLICY", "full", "off",
lambda m: _discord(m, "_get_discord_command_sync_policy")),
("plugins.platforms.discord.adapter", "DISCORD_ALLOW_MENTION_EVERYONE", "true", "false",
lambda m: m._env_bool("DISCORD_ALLOW_MENTION_EVERYONE", False)),
]
def _slack(mod, method):
adapter = object.__new__(mod.SlackAdapter)
adapter.config = PlatformConfig(enabled=True)
return getattr(adapter, method)()
def _signal_reactions(mod):
adapter = object.__new__(mod.SignalAdapter)
adapter.dm_allow_from = {"*"}
return adapter._reactions_enabled()
def _discord(mod, method):
adapter = object.__new__(mod.DiscordAdapter)
adapter.config = PlatformConfig(enabled=True)
adapter.platform = adapter.config and __import__("gateway.config", fromlist=["Platform"]).Platform.DISCORD
return getattr(adapter, method)()
@pytest.mark.parametrize(("module", "var", "default_value", "secondary_value", "resolve"), _SETTINGS,
ids=[f"{m.rsplit('.', 2)[-2]}:{v}" for m, v, *_ in _SETTINGS])
def test_served_secondary_resolves_its_own_setting(monkeypatch, module, var, default_value, secondary_value, resolve):
mod = importlib.import_module(module)
for name in (var, "LINE_CHANNEL_ACCESS_TOKEN", "LINE_CHANNEL_SECRET", "TEAMS_CLIENT_ID", "TEAMS_CLIENT_SECRET",
"TEAMS_TENANT_ID", "SIGNAL_ACCOUNT", "BUZZ_PRIVATE_KEY"):
monkeypatch.delenv(name, raising=False)
creds = {"LINE_CHANNEL_ACCESS_TOKEN": "t", "LINE_CHANNEL_SECRET": "s", "TEAMS_CLIENT_ID": "a",
"TEAMS_CLIENT_SECRET": "b", "TEAMS_TENANT_ID": "c", "SIGNAL_ACCOUNT": "+1", "BUZZ_PRIVATE_KEY": "k"}
standalone, served = _served(monkeypatch, {var: default_value, **creds}, {var: secondary_value, **creds},
lambda: resolve(mod))
assert served == standalone, f"{var}: served={served!r} standalone={standalone!r}"
def test_signal_startup_gate_reads_the_profile_env(monkeypatch):
"""A secondary whose SIGNAL_HTTP_URL/SIGNAL_ACCOUNT live only in its own .env must pass the startup
gate served exactly as it does standalone; a secondary WITHOUT them must not borrow the default's."""
from gateway.platforms import signal as sig
for k in ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"):
monkeypatch.delenv(k, raising=False)
ss.set_multiplex_active(True)
token = ss.set_secret_scope({"SIGNAL_HTTP_URL": "http://secondary.invalid:8080", "SIGNAL_ACCOUNT": "+15550000001"})
try:
assert sig.validate_signal_config(PlatformConfig(enabled=True)) is True
finally:
ss.reset_secret_scope(token)
monkeypatch.setenv("SIGNAL_HTTP_URL", "http://default.invalid:8080")
monkeypatch.setenv("SIGNAL_ACCOUNT", "+15550000000")
token = ss.set_secret_scope({})
try:
assert sig.validate_signal_config(PlatformConfig(enabled=True)) is False
finally:
ss.reset_secret_scope(token)
def test_sms_webhook_listener_is_profile_scoped(monkeypatch):
from plugins.platforms.sms import adapter as sms
for k, v in {"TWILIO_ACCOUNT_SID": "AC0", "TWILIO_AUTH_TOKEN": "tok", "TWILIO_PHONE_NUMBER": "+1",
"SMS_WEBHOOK_PORT": "18039", "SMS_WEBHOOK_HOST": "default-host", "SMS_WEBHOOK_URL": "http://d/"}.items():
monkeypatch.setenv(k, v)
ss.set_multiplex_active(True)
token = ss.set_secret_scope({"TWILIO_ACCOUNT_SID": "AC1", "TWILIO_AUTH_TOKEN": "tok2", "TWILIO_PHONE_NUMBER": "+2",
"SMS_WEBHOOK_PORT": "18139", "SMS_WEBHOOK_HOST": "secondary-host", "SMS_WEBHOOK_URL": "http://s/"})
try:
adapter = sms.SmsAdapter(PlatformConfig(enabled=True))
finally:
ss.reset_secret_scope(token)
assert (adapter._webhook_port, adapter._webhook_host, adapter._webhook_url) == (18139, "secondary-host", "http://s/")