refactor(platforms): one scoped-secret reader and spec-driven enablement/YAML-bridge boilerplate across all adapters
Scoped secrets — `gateway.platforms._shared.get_scoped_secret` is the single implementation of the "scope authoritative, unscoped default-profile falls back to os.environ" read: - plugins/platforms/buzz/adapter.py::_get_scoped_secret (113 LOC, ~100 of which were one docstring paragraph pasted 16x) -> 3-line forwarder over the canonical with `external_fallback=True`. Its one genuine extra rung (one-shot profile-scope build so a Bitwarden-managed key is visible to the startup gate, #95216) moves into `_shared` as that keyword plus `_unscoped_profile_secrets`. - weixin::_wx_secret, matrix::_startup_env_secret, the inline try/except copies in slack (SLACK_APP_TOKEN) and telegram (TELEGRAM_WEBHOOK_SECRET/_URL) -> canonical. - The "extra-first, then scoped env" reader written 11x under 6 names (weixin._extra_or_env, bluebubbles/ntfy/photon/wecom `_setting`, dingtalk `_extra_get`, mattermost `_extra_or_env`, slack `_extra_or_env_flag/_channel_set`, feishu closures) -> `_shared.extra_or_secret`. - `authz_mixin._platform_gate_env` -> `_shared.platform_gate_env`; discord/telegram drop their `_scoped_gate_env` twins; run.py / run_config_loaders.py / slack import it directly. Boilerplate — three table-driven helpers in `_shared` replace the pasted docs template: - `seed_extra_from_env(spec, home_env=)` replaces 8 `_env_enablement` bodies (buzz, google_chat, irc, line, ntfy, photon, simplex, teams; raft is a one-liner and untouched). - `apply_yaml_bridge(cfg, spec)` replaces 7 `_apply_yaml_config` bodies (buzz, dingtalk, feishu, matrix, mattermost, slack, whatsapp); discord/telegram keep bespoke bridges (alias keys, nested `platforms.*.extra`, generic-key exclusions). buzz and mattermost previously bypassed `yaml_env_setter` with hand-rolled `os.environ` writes. - `env_is_connected(*vars)` replaces 5 identical `_is_connected` (discord, homeassistant, mattermost, slack, sms). - 8 identity `_build_adapter` wrappers deleted; `adapter_factory=<Class>`. Behavior change: - buzz `_apply_yaml_config` returned None, so under multiplex a secondary Buzz profile got neither env (correctly skipped) nor `extra` for relay_url/channels/allow_all_users/...; it now seeds `extra` like every other hook. It also wrote reply_in_thread/reply_to_mode to the process env even inside a secondary profile's scope (first-writer-wins leak, #80099 class); it no longer does. BUZZ_POLL_INTERVAL is bridged through the same table. - `home_channel.name` default when `<X>_HOME_CHANNEL_NAME` is unset is now the literal "Home" for all plugins (irc/ntfy/buzz used the chat id; simplex/teams/photon/google_chat already used "Home", as do the built-in platforms in gateway/config_env.py). - weixin's non-secret tunables (send_chunk_*, rate_limit_circuit_*) now read through the scoped reader instead of raw os.getenv — a secondary profile no longer inherits the default's values. - `extra_or_secret` treats a blank string in extra as unset (falls to env) and an explicit False as a real value, the strictest of the merged copies. - slack `reaction_trigger_target` bridges via str(); `reaction_triggers` comma-joins any list-ish value (was list/tuple/set only) — same env text for every real YAML shape. Docs: website/docs/developer-guide/adding-platform-adapters.md (the template the copies were pasted from) and gateway/platforms/ADDING_A_PLATFORM.md now show the helpers and the scoped reader; gateway/AGENTS.md points at the one implementation. Tests: tests/gateway/test_shared_platform_boilerplate.py — every plugin `_env_enablement` reads only through the scoped getter (parametrized over the 8 plugins, spy on the seam, raw `os.getenv`/`get_env_value` asserted untouched); buzz bridge seeds `extra` for a secondary profile and still bridges env for the default; one home-name rule; extra_or_secret contract; external_fallback rung. Existing tests repointed: tests/agent/test_secret_scope_tier1_migration.py, tests/plugins/platforms/buzz/test_buzz_unscoped_requirement_gate.py.
This commit is contained in:
+7
-5
@@ -136,14 +136,16 @@ gateway under the backend, and do NOT "fix" update locks by widening the tree-ki
|
||||
installed per turn by `_profile_runtime_scope`. All profile-level env config — credentials
|
||||
(`app_secret`, tokens) AND authorization (`FEISHU_ALLOWED_USERS`, `{PLATFORM}_ALLOW_ALL_USERS`,
|
||||
`GATEWAY_ALLOW_ALL_USERS`, `group_policy`, `allow_bots`) — is read scope-aware: adapters via
|
||||
`_get_scoped_secret()` (canonical fail-closed copy: `plugins/platforms/feishu/adapter.py`),
|
||||
gateway authz via `_auth_env()` / `_platform_gate_env()` (`authz_mixin.py`). Scope installed +
|
||||
`gateway.platforms._shared.get_scoped_secret` (the ONE implementation; adapters import it as
|
||||
`_get_scoped_secret`; `extra_or_secret` / `seed_extra_from_env` / `env_is_connected` build on it),
|
||||
gateway authz via `_shared.platform_gate_env` (imported by `authz_mixin.py` as `_auth_env`). Scope installed +
|
||||
multiplex active → a scoped miss returns the **default**, NEVER `os.environ` (a leaked allowlist
|
||||
skips the allow-all check and silently rejects every secondary-profile sender, #86905). The
|
||||
unscoped default-profile path (`UnscopedSecretError`) and single-profile deployments keep the
|
||||
`os.environ` read — there it IS the profile's own value. `_get_scoped_secret` is copy-pasted
|
||||
across ~15 adapters: when touching one, verify fail-closed semantics and never reintroduce the
|
||||
`except _UnscopedSecretError: val = os.getenv(...)` fallback-after-miss shape.
|
||||
`os.environ` read — there it IS the profile's own value. Never re-implement the reader in an
|
||||
adapter (the `try get_secret / except UnscopedSecretError: os.getenv` shape drifts into a
|
||||
fallback-after-miss leak); import the shared one. `tests/gateway/test_shared_platform_boilerplate.py`
|
||||
asserts every plugin's `_env_enablement` reads only through it.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+5
-27
@@ -47,30 +47,8 @@ _ALLOW_BOTS_ENV = {
|
||||
}
|
||||
|
||||
|
||||
def _platform_gate_env(name: str, default: str = "") -> str:
|
||||
"""Read an allow/deny gate env var with per-profile isolation.
|
||||
|
||||
With a profile secret scope installed AND multiplexing active, a scoped miss returns ``default``
|
||||
instead of falling through to ``os.environ``, which may hold ANOTHER profile's first-writer
|
||||
bridged value (allowlist leak). Single-profile deployments behave exactly like ``os.getenv``.
|
||||
|
||||
Under multiplex the process env may hold ANOTHER profile's first-writer-bridged value (the YAML→env
|
||||
bridges in the Discord/Telegram adapters' ``_apply_yaml_config`` are first-writer-wins), so falling
|
||||
through would leak profile A's allowlist into profile B (issue #72348).
|
||||
"""
|
||||
if not name:
|
||||
return default
|
||||
with contextlib.suppress(Exception):
|
||||
from agent.secret_scope import current_secret_scope, is_multiplex_active
|
||||
|
||||
scope = current_secret_scope()
|
||||
if scope is not None and is_multiplex_active():
|
||||
val = scope.get(name)
|
||||
return default if val is None else str(val).strip()
|
||||
return (os.getenv(name) or default).strip()
|
||||
|
||||
|
||||
_auth_env = _platform_gate_env
|
||||
# Gate reads use the shared per-profile isolated reader (allowlist leak under multiplex, #72348).
|
||||
from gateway.platforms._shared import platform_gate_env as _auth_env # noqa: E402
|
||||
|
||||
|
||||
def _env_truthy(name: str) -> bool:
|
||||
@@ -492,7 +470,7 @@ class GatewayAuthorizationMixin:
|
||||
# sender_chat posts, channel broadcasts).
|
||||
if is_group and source.chat_id:
|
||||
chat_allowlist_env = _GROUP_CHAT_ENV.get(source.platform, "")
|
||||
if chat_allowlist_env and _allows(_coerce_allow_set(_platform_gate_env(chat_allowlist_env)), source.chat_id):
|
||||
if chat_allowlist_env and _allows(_coerce_allow_set(_auth_env(chat_allowlist_env)), source.chat_id):
|
||||
return True
|
||||
# config.yaml fallback (``extra.group_allowed_chats``): Telegram observe-unmentioned mode
|
||||
# strips user_id, so the env-only check above misses it.
|
||||
@@ -504,7 +482,7 @@ class GatewayAuthorizationMixin:
|
||||
# posts arrive with user=None).
|
||||
if getattr(source, "is_bot", False):
|
||||
allow_bots_var = _ALLOW_BOTS_ENV.get(source.platform)
|
||||
if allow_bots_var and _platform_gate_env(allow_bots_var, "none").lower().strip() in {"mentions", "all"}:
|
||||
if allow_bots_var and _auth_env(allow_bots_var, "none").lower().strip() in {"mentions", "all"}:
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -675,6 +653,6 @@ class GatewayAuthorizationMixin:
|
||||
# Historical: Yuanbao is absent from this allowlist-aware default.
|
||||
env_key = "" if platform == Platform.YUANBAO else _ALLOWED_USERS_ENV.get(platform, "")
|
||||
allowlist_keys = [env_key, _GROUP_USER_ENV.get(platform), _GROUP_CHAT_ENV.get(platform), *allowlist_keys]
|
||||
if any(key and _platform_gate_env(key).strip() for key in allowlist_keys):
|
||||
if any(key and _auth_env(key).strip() for key in allowlist_keys):
|
||||
return "ignore"
|
||||
return "pair"
|
||||
|
||||
@@ -20,15 +20,23 @@ status display, gateway setup, and more.
|
||||
(and an optional `home_channel` dict) from env vars BEFORE the adapter is
|
||||
constructed. Without this, env-only setups don't surface in
|
||||
`hermes gateway status` or `get_connected_platforms()` until the SDK
|
||||
instantiates.
|
||||
instantiates. Build it from a `(ENV_VAR, extra_key, conv)` table with
|
||||
`gateway.platforms._shared.seed_extra_from_env(spec, home_env=...)`; every
|
||||
read goes through `_shared.get_scoped_secret` (multiplex-safe, never
|
||||
`os.getenv`).
|
||||
- `apply_yaml_config_fn: (yaml_cfg, platform_cfg) -> Optional[dict]` —
|
||||
translate this platform's `config.yaml` keys into env vars and/or seed
|
||||
`PlatformConfig.extra` directly. Lets a plugin own its YAML schema
|
||||
instead of growing core `gateway/config.py` boilerplate per platform.
|
||||
Mutating `os.environ` is allowed (use `not os.getenv(...)` guards to
|
||||
preserve env > YAML precedence); the returned dict is merged into
|
||||
`PlatformConfig.extra`. Called during `load_gateway_config()` after
|
||||
the generic shared-key loop and before `_apply_env_overrides()`.
|
||||
translate this platform's `config.yaml` keys into env vars and seed
|
||||
`PlatformConfig.extra`. Lets a plugin own its YAML schema instead of
|
||||
growing core `gateway/config.py` boilerplate per platform. Declare a
|
||||
`(yaml_key, ENV_VAR, kind)` table and return
|
||||
`_shared.apply_yaml_bridge(platform_cfg, TABLE)`: it writes env only when
|
||||
unset (env > YAML), never under a multiplexed secondary profile's scope,
|
||||
and returns the same values for `extra` (read `extra` first in the adapter
|
||||
via `_shared.extra_or_secret`). Called during `load_gateway_config()`
|
||||
after the generic shared-key loop and before `_apply_env_overrides()`.
|
||||
- `is_connected: (config) -> bool` — for env-only platforms use
|
||||
`_shared.env_is_connected("YOUR_TOKEN_VAR", ...)` instead of a hand-rolled
|
||||
`get_env_value` check.
|
||||
- `cron_deliver_env_var: str` — name of the `*_HOME_CHANNEL` env var. When
|
||||
set, `deliver=<name>` cron jobs route to this var without editing
|
||||
`cron/scheduler.py`'s hardcoded sets.
|
||||
|
||||
@@ -6,15 +6,20 @@ import it at module top level without cycles.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Any, Callable
|
||||
from typing import Any, Callable, Iterable, Optional
|
||||
|
||||
# Profile-scoped secret reader for multiplexing support (PR #50094)
|
||||
from agent.secret_scope import UnscopedSecretError as _UnscopedSecretError
|
||||
from agent.secret_scope import get_secret as _scoped_get_secret
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_scoped_secret(name: str, default: Any = None) -> Any:
|
||||
|
||||
def get_scoped_secret(name: str, default: Any = None, *, external_fallback: bool = False) -> Any:
|
||||
"""Scope-aware credential read with the default-profile startup fallback.
|
||||
|
||||
An installed profile secret scope is authoritative: a scoped miss returns
|
||||
@@ -22,18 +27,80 @@ def get_scoped_secret(name: str, default: Any = None) -> Any:
|
||||
The DEFAULT profile constructs and sends *unscoped* under multiplexing,
|
||||
where a bare ``get_secret`` raises ``UnscopedSecretError``; there
|
||||
``os.environ`` is that profile's own value, so fall back to it.
|
||||
|
||||
``external_fallback`` adds one rung for startup gates that run before any
|
||||
scope exists: an unscoped miss consults a one-shot build of the profile's
|
||||
own secret scope, so externally managed credentials (Bitwarden etc., only
|
||||
``BWS_ACCESS_TOKEN`` in ``.env``) are visible to ``check_requirements``.
|
||||
"""
|
||||
try:
|
||||
val = _scoped_get_secret(name, default)
|
||||
val = _scoped_get_secret(name, None)
|
||||
except _UnscopedSecretError:
|
||||
val = os.getenv(name)
|
||||
if val is None and external_fallback and _current_scope() is None:
|
||||
val = _unscoped_profile_secrets().get(name)
|
||||
return val if val is not None else default
|
||||
|
||||
|
||||
def _current_scope():
|
||||
from agent.secret_scope import current_secret_scope
|
||||
return current_secret_scope()
|
||||
|
||||
|
||||
_UNSCOPED_PROFILE_SECRETS: Optional[dict] = None
|
||||
|
||||
|
||||
def _unscoped_profile_secrets() -> dict:
|
||||
"""Process-cached profile secret mapping (external resolvers are slow); failures degrade to {}."""
|
||||
global _UNSCOPED_PROFILE_SECRETS
|
||||
if _UNSCOPED_PROFILE_SECRETS is None:
|
||||
try:
|
||||
from agent.secret_scope import build_profile_secret_scope
|
||||
from hermes_constants import get_hermes_home
|
||||
_UNSCOPED_PROFILE_SECRETS = dict(build_profile_secret_scope(get_hermes_home()))
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Could not build the profile secret scope; externally managed credentials will not be "
|
||||
"visible to the startup gate (#95216)", exc_info=True)
|
||||
_UNSCOPED_PROFILE_SECRETS = {}
|
||||
return _UNSCOPED_PROFILE_SECRETS
|
||||
|
||||
|
||||
def platform_gate_env(name: str, default: str = "") -> str:
|
||||
"""Allow/deny gate env read with per-profile isolation, always stripped.
|
||||
|
||||
With a profile secret scope installed AND multiplexing active, a scoped miss returns ``default``
|
||||
instead of falling through to ``os.environ``, which may hold ANOTHER profile's first-writer
|
||||
bridged value (the YAML→env bridges are first-writer-wins; allowlist leak, #72348).
|
||||
Single-profile deployments behave exactly like ``os.getenv``.
|
||||
"""
|
||||
if not name:
|
||||
return default
|
||||
with contextlib.suppress(Exception):
|
||||
from agent.secret_scope import current_secret_scope, is_multiplex_active
|
||||
|
||||
scope = current_secret_scope()
|
||||
if scope is not None and is_multiplex_active():
|
||||
val = scope.get(name)
|
||||
return default if val is None else str(val).strip()
|
||||
return (os.getenv(name) or default).strip()
|
||||
|
||||
|
||||
def extra_or_secret(extra: Optional[dict], key: str, env: str, default: Any = "") -> Any:
|
||||
"""``config.extra[key]`` when set, else the scoped env var ``env`` (else ``default``).
|
||||
|
||||
``extra`` is the per-profile truth under multiplexing (the YAML→env bridge is skipped for a
|
||||
secondary profile), so it is consulted first; the env read goes through ``get_scoped_secret``.
|
||||
"Unset" is ``None`` or a blank string — an explicit ``False``/``0`` in YAML is a real value
|
||||
(``require_mention: false`` must not fall through to the env default).
|
||||
"""
|
||||
value = (extra or {}).get(key)
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
return get_scoped_secret(env, default)
|
||||
return value
|
||||
|
||||
|
||||
def profile_scoped() -> bool:
|
||||
# --------------------------------------------------------------------------- YAML → env config bridge
|
||||
# (apply_yaml_config_fn, #25443)
|
||||
# ---------------------------------------------------------------------------
|
||||
"""True when running inside a multiplexed secondary profile's scope.
|
||||
|
||||
Secondary-profile adapters are constructed/connected inside
|
||||
@@ -48,6 +115,10 @@ def profile_scoped() -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- YAML → env config bridge
|
||||
# (apply_yaml_config_fn, #25443)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def yaml_env_setter() -> Callable[[str, Any], None]:
|
||||
"""``set_env(name, value)`` for ``apply_yaml_config_fn`` hooks: writes ``os.environ[name]`` only
|
||||
when the var is unset (explicit env wins over YAML) and NEVER while a multiplexed secondary
|
||||
@@ -75,6 +146,73 @@ def send_error(message: Any) -> dict:
|
||||
return _error(str(message))
|
||||
|
||||
|
||||
# kind -> (applies-when predicate over (cfg, key), env encoder). "lower"/"json" bridge whenever the key
|
||||
# is present (YAML ``none`` still writes "none"); "str" skips null/blank, "csv" skips null and leaves
|
||||
# lists to the setter's comma join.
|
||||
_YAML_KINDS: dict[str, tuple[Callable[[dict, str], bool], Callable[[Any], Any]]] = {
|
||||
"lower": (lambda cfg, key: key in cfg, lambda v: str(v).lower()),
|
||||
"str": (lambda cfg, key: cfg.get(key) not in (None, ""), str),
|
||||
"csv": (lambda cfg, key: cfg.get(key) is not None, lambda v: v),
|
||||
"json": (lambda cfg, key: key in cfg, json.dumps),
|
||||
}
|
||||
|
||||
|
||||
def apply_yaml_bridge(cfg: dict, spec: Iterable[tuple[str, str, str]]) -> dict | None:
|
||||
"""Table-driven ``apply_yaml_config_fn`` body: for each ``(yaml_key, ENV_VAR, kind)`` row seed the
|
||||
original YAML value into the returned ``extra`` and bridge it to env through ``yaml_env_setter``
|
||||
(env wins; skipped under a secondary profile's scope). ``None`` when nothing matched.
|
||||
"""
|
||||
set_env = yaml_env_setter()
|
||||
seeded: dict = {}
|
||||
for key, env, kind in spec:
|
||||
applies, encode = _YAML_KINDS[kind]
|
||||
if applies(cfg, key):
|
||||
seeded[key] = cfg[key]
|
||||
set_env(env, encode(cfg[key]))
|
||||
return seeded or None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- env → extra seeding
|
||||
# (env_enablement_fn)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def seed_extra_from_env(spec: Iterable[tuple[str, str, Callable[[str], Any] | None]], *,
|
||||
home_env: str | None = None, home_default: str = "") -> dict:
|
||||
"""Table-driven ``env_enablement_fn`` body: for each ``(ENV_VAR, extra_key, conv)`` row read the
|
||||
profile-scoped value, skip it when blank or when ``conv`` raises ``ValueError``, else seed
|
||||
``conv(value)`` (``None`` conv keeps the stripped string).
|
||||
|
||||
``home_env`` seeds ``home_channel`` as ``{"chat_id", "name"}`` from ``<home_env>`` (else
|
||||
``home_default``) with ``<home_env>_NAME`` naming it — the core hook lifts that dict into a
|
||||
``HomeChannel``. The name falls back to the literal ``"Home"``, the same rule the built-in
|
||||
platforms use.
|
||||
"""
|
||||
seed: dict = {}
|
||||
for env, key, conv in spec:
|
||||
raw = str(get_scoped_secret(env, "") or "").strip()
|
||||
if not raw:
|
||||
continue
|
||||
with contextlib.suppress(ValueError):
|
||||
seed[key] = conv(raw) if conv else raw
|
||||
if home_env:
|
||||
home = str(get_scoped_secret(home_env, "") or "").strip() or home_default
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": get_scoped_secret(f"{home_env}_NAME", "Home")}
|
||||
return seed
|
||||
|
||||
|
||||
def env_is_connected(*names: str) -> Callable[[Any], bool]:
|
||||
"""``is_connected`` for platforms whose only configuration is env: True when every ``names`` var is
|
||||
non-blank. Resolves ``hermes_cli.gateway.get_env_value`` at call time (scope-aware, .env-backed) so
|
||||
setup-status tests that patch it see the same value."""
|
||||
|
||||
def is_connected(config: Any) -> bool:
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return all((gateway_mod.get_env_value(name) or "").strip() for name in names)
|
||||
|
||||
return is_connected
|
||||
|
||||
|
||||
def coerce_port(value: Any, default: int) -> int:
|
||||
"""``int(value)`` or ``default`` when unparseable."""
|
||||
try:
|
||||
|
||||
@@ -17,7 +17,7 @@ from urllib.parse import parse_qs, quote
|
||||
import httpx
|
||||
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret
|
||||
from gateway.platforms._shared import extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret
|
||||
from gateway.platforms.base import (
|
||||
BasePlatformAdapter, SendResult,
|
||||
cache_image_from_bytes_async, cache_audio_from_bytes_async, cache_document_from_bytes_async,
|
||||
@@ -92,11 +92,6 @@ def _closed_ext(mime: str, overrides: Dict[str, str], fallback: str) -> str:
|
||||
fallback=fallback) or fallback
|
||||
|
||||
|
||||
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 _get_scoped_secret(env, default)
|
||||
|
||||
|
||||
def _temp_guid() -> str:
|
||||
return f"temp-{datetime.utcnow().timestamp()}"
|
||||
|
||||
@@ -118,11 +113,11 @@ class BlueBubblesAdapter(BasePlatformAdapter):
|
||||
def __init__(self, config: PlatformConfig):
|
||||
super().__init__(config, Platform.BLUEBUBBLES)
|
||||
extra = config.extra or {}
|
||||
self.server_url = _normalize_server_url(_setting(extra, "server_url", "BLUEBUBBLES_SERVER_URL"))
|
||||
self.server_url = _normalize_server_url(_extra_or_secret(extra, "server_url", "BLUEBUBBLES_SERVER_URL"))
|
||||
self.password = extra.get("password") or _get_scoped_secret("BLUEBUBBLES_PASSWORD", "")
|
||||
self.webhook_host = _setting(extra, "webhook_host", "BLUEBUBBLES_WEBHOOK_HOST", DEFAULT_WEBHOOK_HOST)
|
||||
self.webhook_port = int(_setting(extra, "webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", str(DEFAULT_WEBHOOK_PORT)))
|
||||
path = str(_setting(extra, "webhook_path", "BLUEBUBBLES_WEBHOOK_PATH", DEFAULT_WEBHOOK_PATH))
|
||||
self.webhook_host = _extra_or_secret(extra, "webhook_host", "BLUEBUBBLES_WEBHOOK_HOST", DEFAULT_WEBHOOK_HOST)
|
||||
self.webhook_port = int(_extra_or_secret(extra, "webhook_port", "BLUEBUBBLES_WEBHOOK_PORT", str(DEFAULT_WEBHOOK_PORT)))
|
||||
path = str(_extra_or_secret(extra, "webhook_path", "BLUEBUBBLES_WEBHOOK_PATH", DEFAULT_WEBHOOK_PATH))
|
||||
self.webhook_path = path if path.startswith("/") else f"/{path}"
|
||||
self.send_read_receipts = bool(extra.get("send_read_receipts", True))
|
||||
_require_mention = extra.get("require_mention")
|
||||
|
||||
@@ -37,30 +37,12 @@ from gateway.platforms.base import (
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from hermes_constants import get_hermes_home
|
||||
from utils import atomic_json_write
|
||||
from agent.secret_scope import UnscopedSecretError, get_secret
|
||||
|
||||
|
||||
def _wx_secret(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
"""Scope-aware WEIXIN_* read. Secondary profiles run scoped: a miss returns ``default``
|
||||
(never borrow ``os.environ``). The DEFAULT profile runs *unscoped* under multiplexing,
|
||||
where ``get_secret`` raises; there ``os.environ`` is its own value, so fall back.
|
||||
|
||||
Same pattern as the Slack ``SLACK_APP_TOKEN`` read (#59739) and WhatsApp's ``_get_wsecret``.
|
||||
"""
|
||||
try:
|
||||
return get_secret(name, default)
|
||||
except UnscopedSecretError:
|
||||
return os.getenv(name, default)
|
||||
from gateway.platforms._shared import extra_or_secret as _extra_or_env, get_scoped_secret as _wx_secret
|
||||
|
||||
|
||||
def _extra_or_secret(extra: Dict[str, Any], key: str, default: str = "") -> str:
|
||||
"""``config.extra[key]`` first, else the scoped secret ``WEIXIN_<KEY>``; stripped."""
|
||||
return str(extra.get(key) or _wx_secret(f"WEIXIN_{key.upper()}", default)).strip()
|
||||
|
||||
|
||||
def _extra_or_env(extra: Dict[str, Any], key: str, default: str) -> Any:
|
||||
"""``config.extra[key]`` first, else plain ``os.getenv("WEIXIN_<KEY>", default)`` (non-secret tunables)."""
|
||||
return extra.get(key) or os.getenv(f"WEIXIN_{key.upper()}", default)
|
||||
"""``config.extra[key]`` first, else the scoped ``WEIXIN_<KEY>``; stripped."""
|
||||
return str(_extra_or_env(extra, key, f"WEIXIN_{key.upper()}", default)).strip()
|
||||
|
||||
|
||||
ILINK_BASE_URL = "https://ilinkai.weixin.qq.com"
|
||||
@@ -714,13 +696,13 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
|
||||
self._base_url = _extra_or_secret(extra, "base_url", ILINK_BASE_URL).rstrip("/")
|
||||
self._cdn_base_url = _extra_or_secret(extra, "cdn_base_url", WEIXIN_CDN_BASE_URL).rstrip("/")
|
||||
# Tunables: ``extra.<key>`` else env ``WEIXIN_<KEY>`` (e.g. WEIXIN_SEND_CHUNK_RETRIES).
|
||||
self._send_chunk_delay_seconds = float(_extra_or_env(extra, "send_chunk_delay_seconds", "1.5"))
|
||||
self._send_chunk_retries = int(_extra_or_env(extra, "send_chunk_retries", "4"))
|
||||
self._send_chunk_retry_delay_seconds = float(_extra_or_env(extra, "send_chunk_retry_delay_seconds", "1.0"))
|
||||
self._send_chunk_delay_seconds = float(_extra_or_secret(extra, "send_chunk_delay_seconds", "1.5"))
|
||||
self._send_chunk_retries = int(_extra_or_secret(extra, "send_chunk_retries", "4"))
|
||||
self._send_chunk_retry_delay_seconds = float(_extra_or_secret(extra, "send_chunk_retry_delay_seconds", "1.0"))
|
||||
self._send_text_gate = asyncio.Lock()
|
||||
self._rate_limit_circuit_threshold = max(1, int(_extra_or_env(extra, "rate_limit_circuit_threshold", "1")))
|
||||
self._rate_limit_circuit_window_seconds = float(_extra_or_env(extra, "rate_limit_circuit_window_seconds", "30.0"))
|
||||
self._rate_limit_circuit_open_seconds = float(_extra_or_env(extra, "rate_limit_circuit_open_seconds", "30.0"))
|
||||
self._rate_limit_circuit_threshold = max(1, int(_extra_or_secret(extra, "rate_limit_circuit_threshold", "1")))
|
||||
self._rate_limit_circuit_window_seconds = float(_extra_or_secret(extra, "rate_limit_circuit_window_seconds", "30.0"))
|
||||
self._rate_limit_circuit_open_seconds = float(_extra_or_secret(extra, "rate_limit_circuit_open_seconds", "30.0"))
|
||||
self._rate_limit_circuit_until, self._rate_limit_events = 0.0, [] # type: float, List[float]
|
||||
self._dm_policy = _extra_or_secret(extra, "dm_policy", "pairing").lower()
|
||||
self._group_policy = _extra_or_secret(extra, "group_policy", "disabled").lower()
|
||||
|
||||
+1
-1
@@ -1151,7 +1151,7 @@ def _slack_ignored_channels_from_gateway_config(config: Any, adapter: Any = None
|
||||
if raw is None:
|
||||
# Top-level ``slack.ignored_channels`` arrives via the plugin's YAML→env bridge, not PlatformConfig.extra
|
||||
# (#46925); scoped read so a secondary never inherits the default profile's list (first-writer env).
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
from gateway.platforms._shared import platform_gate_env as _platform_gate_env
|
||||
raw = _platform_gate_env("SLACK_IGNORED_CHANNELS") or None
|
||||
return _csv_or_list_to_set(raw)
|
||||
|
||||
|
||||
@@ -386,7 +386,7 @@ class GatewayConfigLoadersMixin:
|
||||
(``_completion_event_scope``). The env override reads through the secret scope so a served
|
||||
secondary sees its own ``.env`` value, not the launch profile's ``os.environ``."""
|
||||
from gateway.run import _load_gateway_config
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
from gateway.platforms._shared import platform_gate_env as _platform_gate_env
|
||||
mode = _platform_gate_env("HERMES_BACKGROUND_NOTIFICATIONS")
|
||||
if not mode:
|
||||
raw = cfg_get(_load_gateway_config(), "display", "background_process_notifications")
|
||||
|
||||
@@ -28,148 +28,18 @@ from urllib.parse import urlsplit, urlunsplit
|
||||
# Profile-scoped read (adapter startup, Slack pattern #59739): a scoped read honors the profile's own
|
||||
# secret; only an UNSCOPED read under multiplex (default-profile startup loop) falls back to the process
|
||||
# env, which is that profile's own value.
|
||||
from agent.secret_scope import (
|
||||
UnscopedSecretError as _UnscopedSecretError, current_secret_scope as _current_secret_scope,
|
||||
get_secret as _scoped_get_secret, is_multiplex_active as _is_multiplex_active,
|
||||
from agent.secret_scope import is_multiplex_active as _is_multiplex_active
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, get_scoped_secret as _shared_scoped_secret, profile_scoped as _profile_scoped,
|
||||
seed_extra_from_env as _seed_extra_from_env,
|
||||
)
|
||||
from gateway.platforms._shared import profile_scoped as _profile_scoped, send_error
|
||||
from gateway.platforms._shared import send_error
|
||||
|
||||
|
||||
def _get_scoped_secret(name, default=None):
|
||||
"""Scope-aware credential read: an active scope is authoritative (a miss is ``default``, never an env
|
||||
borrow). Unscoped adds one rung over ``_shared``: the startup gate runs before any scope exists, so
|
||||
externally managed secrets are consulted via a one-shot profile-scope build.
|
||||
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and connects *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash
|
||||
startup/reconnect (#70652 class); there ``os.environ`` is that profile's own value, so fall back to it.
|
||||
Same pattern as ``whatsapp_common._get_wsecret`` and the WeCom/IRC/ntfy plugin adapters.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
Secondary profiles construct their adapters under a profile secret scope -- the scope is authoritative
|
||||
and a scoped miss returns ``default`` (no cross-profile borrow from ``os.environ``, which may hold
|
||||
another profile's value). The DEFAULT profile's adapter constructs and sends *unscoped* under
|
||||
multiplexing, where a bare ``get_secret`` would raise ``UnscopedSecretError`` and crash this path; there
|
||||
``os.environ`` is that profile's own value, so fall back to it. Same pattern as the Slack
|
||||
``SLACK_APP_TOKEN`` read (#59739) and ``gateway/platforms/whatsapp_common.py::_get_wsecret``.
|
||||
"""
|
||||
try:
|
||||
val = _scoped_get_secret(name, None)
|
||||
except _UnscopedSecretError:
|
||||
# DEFAULT profile's adapter constructs/connects outside any _profile_runtime_scope under
|
||||
# multiplexing; os.environ is that profile's own value there. Same pattern as Slack SLACK_APP_TOKEN
|
||||
# (#59739) and the Matrix recovery key. A *scoped* miss still returns the default (no cross-profile
|
||||
# borrow).
|
||||
val = os.getenv(name)
|
||||
if val is None and _current_secret_scope() is None:
|
||||
val = _unscoped_profile_secrets().get(name)
|
||||
return val if val is not None else default
|
||||
|
||||
|
||||
_UNSCOPED_PROFILE_SECRETS: Optional[Dict[str, str]] = None
|
||||
|
||||
|
||||
def _unscoped_profile_secrets() -> Dict[str, str]:
|
||||
"""Process-cached profile secret mapping (external resolvers are slow); failures degrade to {}."""
|
||||
global _UNSCOPED_PROFILE_SECRETS
|
||||
if _UNSCOPED_PROFILE_SECRETS is None:
|
||||
try:
|
||||
from agent.secret_scope import build_profile_secret_scope
|
||||
from hermes_constants import get_hermes_home
|
||||
_UNSCOPED_PROFILE_SECRETS = dict(build_profile_secret_scope(get_hermes_home()))
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Buzz requirement probe could not build the profile secret "
|
||||
"scope; Bitwarden-managed credentials will not be visible "
|
||||
"to the startup gate (#95216)",
|
||||
exc_info=True,
|
||||
)
|
||||
_UNSCOPED_PROFILE_SECRETS = {}
|
||||
return _UNSCOPED_PROFILE_SECRETS
|
||||
"""Buzz reads consult a one-shot profile-scope build when unscoped: ``check_requirements`` runs at
|
||||
startup before any scope exists, so Bitwarden-managed keys would otherwise be invisible (#95216)."""
|
||||
return _shared_scoped_secret(name, default, external_fallback=True)
|
||||
|
||||
|
||||
def _scoped_platform_setting(env_name, extra, key):
|
||||
@@ -1939,66 +1809,43 @@ def is_connected(config) -> bool:
|
||||
return validate_config(config)
|
||||
|
||||
|
||||
# (extra key, env var, kind): "str" bridges truthy values as-is, "csv" joins lists,
|
||||
# "flag" lowercases when present, "thread" lowercases and ignores profile scope.
|
||||
_YAML_BRIDGE = (
|
||||
_YAML_BRIDGE = ( # (extra key, env var, kind) for apply_yaml_bridge
|
||||
("relay_url", "BUZZ_RELAY_URL", "str"), ("cli_path", "BUZZ_CLI_PATH", "str"),
|
||||
("home_channel", "BUZZ_HOME_CHANNEL", "str"), ("transport", "BUZZ_TRANSPORT", "str"),
|
||||
("poll_interval", "BUZZ_POLL_INTERVAL", "str"),
|
||||
("channels", "BUZZ_CHANNELS", "csv"), ("allowed_users", "BUZZ_ALLOWED_USERS", "csv"),
|
||||
("reaction_only_users", "BUZZ_REACTION_ONLY_USERS", "csv"), ("allow_all_users", "BUZZ_ALLOW_ALL_USERS", "flag"),
|
||||
("require_mention", "BUZZ_REQUIRE_MENTION", "flag"), ("reply_in_thread", "BUZZ_REPLY_IN_THREAD", "thread"),
|
||||
("reply_to_mode", "BUZZ_REPLY_TO_MODE", "thread"),
|
||||
("reaction_only_users", "BUZZ_REACTION_ONLY_USERS", "csv"), ("allow_all_users", "BUZZ_ALLOW_ALL_USERS", "lower"),
|
||||
("require_mention", "BUZZ_REQUIRE_MENTION", "lower"), ("reply_in_thread", "BUZZ_REPLY_IN_THREAD", "lower"),
|
||||
("reply_to_mode", "BUZZ_REPLY_TO_MODE", "lower"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, buzz_cfg: dict) -> Optional[dict]:
|
||||
"""Bridge ``buzz.extra`` into ``BUZZ_*`` env so a config.yaml-only setup passes the env-reading gate.
|
||||
Env wins over YAML; ``BUZZ_PRIVATE_KEY`` is never sourced from config.yaml."""
|
||||
"""``apply_yaml_config_fn``: bridge ``buzz.extra`` into ``BUZZ_*`` env (env wins; skipped under a
|
||||
secondary profile's scope, #98738) and seed the same keys into the returned ``extra`` so each profile's
|
||||
adapter reads its own. ``BUZZ_PRIVATE_KEY`` is never sourced from config.yaml."""
|
||||
extra = buzz_cfg.get("extra", buzz_cfg) or {}
|
||||
if not isinstance(extra, dict):
|
||||
return None
|
||||
# A secondary profile must NOT write the process-global env (first-writer-wins would pin it for every profile).
|
||||
# Under multiplex, a secondary profile's config loads inside its runtime scope; its values must NOT be
|
||||
# written to the process-global env, where first-writer-wins would pin them for every other profile
|
||||
# (issue #72348 Telegram/Discord mirror, Buzz side of #98738). Its adapter reads the profile's
|
||||
# PlatformConfig.extra directly instead.
|
||||
skip_env_bridge = _profile_scoped()
|
||||
interval = extra.get("poll_interval")
|
||||
if interval is not None and not skip_env_bridge and not os.getenv("BUZZ_POLL_INTERVAL"):
|
||||
os.environ["BUZZ_POLL_INTERVAL"] = str(interval)
|
||||
for src, env, kind in _YAML_BRIDGE:
|
||||
val = extra.get(src)
|
||||
missing = {"str": not val, "csv": val is None}.get(kind, src not in extra)
|
||||
if missing or (kind != "thread" and skip_env_bridge) or os.getenv(env):
|
||||
continue
|
||||
if kind == "csv" and isinstance(val, (list, tuple)):
|
||||
val = ",".join(str(v) for v in val)
|
||||
os.environ[env] = str(val).lower() if kind in ("flag", "thread") else str(val)
|
||||
return None
|
||||
return _apply_yaml_bridge(extra, _YAML_BRIDGE)
|
||||
|
||||
|
||||
|
||||
def _env_enablement() -> Optional[dict]:
|
||||
"""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)."""
|
||||
"""``env_enablement_fn``: 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).
|
||||
Cron delivery target defaults to the first watched channel."""
|
||||
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 := str(_get_scoped_secret("BUZZ_CHANNELS", "") or "").strip():
|
||||
seed["channels"] = [c.strip() for c in channels.split(",") if c.strip()]
|
||||
if interval := str(_get_scoped_secret("BUZZ_POLL_INTERVAL", "") or "").strip():
|
||||
try:
|
||||
seed["poll_interval"] = float(interval)
|
||||
except ValueError:
|
||||
pass
|
||||
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 = str(_get_scoped_secret("BUZZ_HOME_CHANNEL", "") or "").strip() or (seed.get("channels") or [""])[0]
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("BUZZ_HOME_CHANNEL_NAME", home)}
|
||||
return seed
|
||||
seed = _seed_extra_from_env((
|
||||
("BUZZ_CHANNELS", "channels", lambda v: [c.strip() for c in v.split(",") if c.strip()]),
|
||||
("BUZZ_POLL_INTERVAL", "poll_interval", float), ("BUZZ_CLI_PATH", "cli_path", None),
|
||||
))
|
||||
home = _seed_extra_from_env((), home_env="BUZZ_HOME_CHANNEL", home_default=(seed.get("channels") or [""])[0])
|
||||
return {"relay_url": relay, **seed, **home}
|
||||
|
||||
|
||||
|
||||
async def _standalone_send(
|
||||
|
||||
@@ -6,7 +6,6 @@ Requires ``pip install "dingtalk-stream>=0.20" httpx``. config.yaml ``platforms.
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
import uuid
|
||||
@@ -50,7 +49,10 @@ from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.helpers import MessageDeduplicator, compile_mention_patterns
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error, yaml_env_setter as _yaml_env_setter
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, extra_or_secret as _extra_or_secret,
|
||||
get_scoped_secret as _get_scoped_secret, send_error
|
||||
)
|
||||
from plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text
|
||||
|
||||
|
||||
@@ -250,20 +252,13 @@ class DingTalkAdapter(BasePlatformAdapter):
|
||||
store.clear()
|
||||
logger.info("[%s] Disconnected", self.name)
|
||||
|
||||
def _extra_get(self, key: str, env_name: str = "", env_default: str = ""):
|
||||
"""config.extra[key]; when *env_name* is given, absent keys fall back to the env var.
|
||||
|
||||
Scoped read: under multiplex os.environ is the DEFAULT profile's allowlist/policy."""
|
||||
value = self.config.extra.get(key) if self.config.extra else None
|
||||
return _get_scoped_secret(env_name, env_default) if value is None and env_name else value
|
||||
|
||||
def _csv_setting(self, key: str, env_name: str) -> Set[str]:
|
||||
"""List/CSV setting from config.extra[key], falling back to the env var."""
|
||||
return _csv_set(self._extra_get(key, env_name))
|
||||
return _csv_set(_extra_or_secret(self.config.extra, key, env_name))
|
||||
|
||||
def _dingtalk_require_mention(self) -> bool:
|
||||
"""Whether group chats require an explicit bot trigger."""
|
||||
configured = self._extra_get("require_mention", "DINGTALK_REQUIRE_MENTION", "false")
|
||||
configured = _extra_or_secret(self.config.extra, "require_mention", "DINGTALK_REQUIRE_MENTION", "false")
|
||||
return configured.lower() in _TRUTHY if isinstance(configured, str) else bool(configured)
|
||||
|
||||
def _dingtalk_allowed_chats(self) -> Set[str]:
|
||||
@@ -272,7 +267,7 @@ class DingTalkAdapter(BasePlatformAdapter):
|
||||
|
||||
def _compile_mention_patterns(self) -> List[re.Pattern]:
|
||||
"""Compile optional regex wake-word patterns (config list, or env as JSON / lines / CSV)."""
|
||||
patterns = self._extra_get("mention_patterns")
|
||||
patterns = (self.config.extra or {}).get("mention_patterns")
|
||||
if patterns is None and (raw := str(_get_scoped_secret("DINGTALK_MENTION_PATTERNS", "") or "").strip()):
|
||||
try:
|
||||
patterns = json.loads(raw)
|
||||
@@ -656,9 +651,9 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
|
||||
|
||||
def interactive_setup() -> None:
|
||||
"""Configure DingTalk — QR scan (recommended) or manual credential entry."""
|
||||
from hermes_cli.config import get_env_value, save_env_value
|
||||
from hermes_cli.config import save_env_value
|
||||
from hermes_cli.setup import prompt_choice
|
||||
from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_success, print_warning
|
||||
from hermes_cli.cli_output import prompt, print_header, print_success, print_warning
|
||||
from hermes_cli.setup_platforms import declines_reconfigure
|
||||
print_header("DingTalk")
|
||||
if declines_reconfigure("DingTalk", "Reconfigure DingTalk?", "DINGTALK_CLIENT_ID"):
|
||||
@@ -701,29 +696,23 @@ def _nested_allowed_users(yaml_cfg: dict, dingtalk_cfg: dict):
|
||||
return None
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, dingtalk_cfg: dict) -> dict | None:
|
||||
"""Translate config.yaml dingtalk: keys into DINGTALK_* env vars + ``PlatformConfig.extra`` (apply_yaml_config_fn);
|
||||
env wins. The docs put the allowlist at ``gateway.platforms.dingtalk.extra.allowed_users`` but gateway authz only
|
||||
consults DINGTALK_ALLOWED_USERS, so nested-only allowlists are bridged too.
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
|
||||
("require_mention", "DINGTALK_REQUIRE_MENTION", "lower"), ("mention_patterns", "DINGTALK_MENTION_PATTERNS", "json"),
|
||||
("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS", "csv"), ("allowed_chats", "DINGTALK_ALLOWED_CHATS", "csv"),
|
||||
("allowed_users", "DINGTALK_ALLOWED_USERS", "csv"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, dingtalk_cfg: dict) -> dict | None:
|
||||
"""``apply_yaml_config_fn`` (#24849): config.yaml dingtalk: keys → DINGTALK_* env (env wins; skipped under a
|
||||
multiplexed secondary profile's scope) + ``PlatformConfig.extra``. The docs put the allowlist at
|
||||
``gateway.platforms.dingtalk.extra.allowed_users`` but gateway authz only consults DINGTALK_ALLOWED_USERS,
|
||||
so nested-only allowlists are bridged too."""
|
||||
cfg = dict(dingtalk_cfg)
|
||||
if cfg.get("allowed_users") is None:
|
||||
cfg["allowed_users"] = _nested_allowed_users(yaml_cfg, dingtalk_cfg)
|
||||
return _apply_yaml_bridge(cfg, _YAML_BRIDGE)
|
||||
|
||||
Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy dingtalk_cfg block from
|
||||
gateway/config.py::load_gateway_config(). The env write is skipped under a multiplexed secondary profile's
|
||||
scope; the adapter's ``_extra_get`` readers consume the seeded extra.
|
||||
"""
|
||||
_set_env = _yaml_env_setter()
|
||||
seeded: dict = {}
|
||||
for key, env, encode in (("require_mention", "DINGTALK_REQUIRE_MENTION", lambda v: str(v).lower()), ("mention_patterns", "DINGTALK_MENTION_PATTERNS", json.dumps)):
|
||||
if key in dingtalk_cfg:
|
||||
seeded[key] = dingtalk_cfg[key]
|
||||
_set_env(env, encode(dingtalk_cfg[key]))
|
||||
allowed = dingtalk_cfg.get("allowed_users")
|
||||
for key, env, value in (("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS", dingtalk_cfg.get("free_response_chats")),
|
||||
("allowed_chats", "DINGTALK_ALLOWED_CHATS", dingtalk_cfg.get("allowed_chats")),
|
||||
("allowed_users", "DINGTALK_ALLOWED_USERS", _nested_allowed_users(yaml_cfg, dingtalk_cfg) if allowed is None else allowed)):
|
||||
if value is not None:
|
||||
seeded[key] = value
|
||||
_set_env(env, value)
|
||||
return seeded or None
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
@@ -731,14 +720,11 @@ def _is_connected(config) -> bool:
|
||||
return all(_credentials(getattr(config, "extra", {})))
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
return DingTalkAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
ctx.register_platform(
|
||||
name="dingtalk", label="DingTalk", adapter_factory=_build_adapter, check_fn=dingtalk_deps_present,
|
||||
name="dingtalk", label="DingTalk", adapter_factory=DingTalkAdapter, check_fn=dingtalk_deps_present,
|
||||
ensure_deps_fn=ensure_dingtalk_deps, is_connected=_is_connected, validate_config=_is_connected,
|
||||
required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"], install_hint="pip install 'dingtalk-stream>=0.20' httpx",
|
||||
setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="DINGTALK_ALLOWED_USERS",
|
||||
|
||||
@@ -270,7 +270,10 @@ from gateway.platforms.base import (
|
||||
)
|
||||
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
|
||||
from tools.url_safety import is_safe_url
|
||||
from gateway.platforms._shared import send_error, yaml_env_setter as _yaml_env_setter
|
||||
from gateway.platforms._shared import (
|
||||
env_is_connected as _env_is_connected, platform_gate_env as _scoped_gate_env, send_error,
|
||||
yaml_env_setter as _yaml_env_setter
|
||||
)
|
||||
|
||||
|
||||
async def _read_url_image_with_redirect_guard(
|
||||
@@ -546,15 +549,6 @@ _GATE_ENV_KEYS = (
|
||||
)
|
||||
|
||||
|
||||
def _scoped_gate_env(name: str, default: str = "") -> str:
|
||||
"""Scope-aware gate env read: profile secret scope first under multiplex."""
|
||||
try:
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
return _platform_gate_env(name, default)
|
||||
except Exception:
|
||||
return (os.getenv(name) or default).strip()
|
||||
|
||||
|
||||
def _multiplex_active() -> bool:
|
||||
"""True when the gateway is running in multiplex_profiles mode."""
|
||||
try:
|
||||
@@ -7026,24 +7020,16 @@ def _apply_yaml_config(yaml_cfg: dict, discord_cfg: dict) -> dict | None:
|
||||
return seeded_extra or None
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
"""Connected when DISCORD_BOT_TOKEN is set.
|
||||
Looks up ``hermes_cli.gateway.get_env_value`` at call time so tests can patch it (ambient env)."""
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return bool((gateway_mod.get_env_value("DISCORD_BOT_TOKEN") or "").strip())
|
||||
_is_connected = _env_is_connected("DISCORD_BOT_TOKEN")
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
"""Factory wrapper that constructs DiscordAdapter from a PlatformConfig."""
|
||||
return DiscordAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
ctx.register_platform(
|
||||
name="discord",
|
||||
label="Discord",
|
||||
adapter_factory=_build_adapter,
|
||||
adapter_factory=DiscordAdapter,
|
||||
check_fn=discord_deps_present,
|
||||
ensure_deps_fn=check_discord_requirements,
|
||||
is_connected=_is_connected,
|
||||
|
||||
@@ -804,15 +804,11 @@ def _is_connected(config) -> bool:
|
||||
return bool((gateway_mod.get_env_value("EMAIL_ADDRESS") or "").strip())
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
"""Factory wrapper that constructs EmailAdapter from a PlatformConfig."""
|
||||
return EmailAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
ctx.register_platform(
|
||||
name="email", label="Email", adapter_factory=_build_adapter, check_fn=check_email_requirements, is_connected=_is_connected,
|
||||
name="email", label="Email", adapter_factory=EmailAdapter, check_fn=check_email_requirements, is_connected=_is_connected,
|
||||
required_env=["EMAIL_ADDRESS", "EMAIL_PASSWORD", "EMAIL_SMTP_HOST"],
|
||||
install_hint="Email uses the Python stdlib (smtplib/imaplib) — no extra deps", allowed_users_env="EMAIL_ALLOWED_USERS",
|
||||
allow_all_env="EMAIL_ALLOW_ALL_USERS", cron_deliver_env_var="EMAIL_HOME_ADDRESS", standalone_sender_fn=_standalone_send,
|
||||
|
||||
@@ -92,7 +92,10 @@ from gateway.status import acquire_scoped_lock, release_scoped_lock
|
||||
from hermes_constants import get_hermes_home
|
||||
from utils import atomic_json_write, env_float, env_int
|
||||
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error, yaml_env_setter as _yaml_env_setter
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, extra_or_secret as _shared_extra_or_secret,
|
||||
get_scoped_secret as _get_scoped_secret, send_error
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -1268,11 +1271,10 @@ class FeishuAdapter(BasePlatformAdapter):
|
||||
def _secret(name: str, default: str = "") -> str:
|
||||
return _get_scoped_secret(name, default).strip()
|
||||
|
||||
def _extra_or_secret(key: str, env: str) -> str:
|
||||
return str(extra.get(key) or _get_scoped_secret(env, "")).strip()
|
||||
def _extra_or_secret(key: str, env: str, default: str = "") -> str:
|
||||
return str(_shared_extra_or_secret(extra, key, env, default)).strip()
|
||||
|
||||
def _extra_or_env(key: str, env: str, default: str) -> str:
|
||||
return str(extra.get(key) or _get_scoped_secret(env, default)).strip()
|
||||
_extra_or_env = _extra_or_secret
|
||||
|
||||
raw_group_rules = extra.get("group_rules", {})
|
||||
group_rules: Dict[str, FeishuGroupRule] = {}
|
||||
@@ -4159,9 +4161,9 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
|
||||
|
||||
def interactive_setup() -> None:
|
||||
"""Interactive setup for Feishu / Lark — scan-to-create or manual creds (CLI helpers lazy-imported)."""
|
||||
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
|
||||
from hermes_cli.config import remove_env_value, save_env_value
|
||||
from hermes_cli.setup import prompt_choice
|
||||
from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success, print_warning
|
||||
from hermes_cli.cli_output import prompt, print_header, print_info, print_success, print_warning
|
||||
from hermes_cli.setup_platforms import declines_reconfigure
|
||||
|
||||
print_header("Feishu / Lark")
|
||||
@@ -4277,17 +4279,11 @@ def interactive_setup() -> None:
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, feishu_cfg: dict) -> dict | None:
|
||||
"""apply_yaml_config_fn: bridge config.yaml feishu.allow_bots to FEISHU_ALLOW_BOTS (env wins) and seed
|
||||
``extra.allow_bots`` so a multiplexed secondary profile's adapter reads its own value.
|
||||
"""``apply_yaml_config_fn`` (#24849): bridge config.yaml feishu.allow_bots to FEISHU_ALLOW_BOTS (env wins) and
|
||||
seed ``extra.allow_bots`` so a multiplexed secondary profile's adapter reads its own value."""
|
||||
seeded = _apply_yaml_bridge(feishu_cfg, (("allow_bots", "FEISHU_ALLOW_BOTS", "lower"),))
|
||||
return {"allow_bots": str(seeded["allow_bots"]).lower()} if seeded else None
|
||||
|
||||
Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy feishu_cfg block from
|
||||
gateway/config.py::load_gateway_config() (allow_bots). Env vars take precedence over YAML.
|
||||
"""
|
||||
if "allow_bots" not in feishu_cfg:
|
||||
return None
|
||||
_set_env = _yaml_env_setter()
|
||||
_set_env("FEISHU_ALLOW_BOTS", str(feishu_cfg["allow_bots"]).lower())
|
||||
return {"allow_bots": str(feishu_cfg["allow_bots"]).lower()}
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
@@ -4296,15 +4292,11 @@ def _is_connected(config) -> bool:
|
||||
return bool(extra.get("app_id"))
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
"""Factory wrapper that constructs FeishuAdapter from a PlatformConfig."""
|
||||
return FeishuAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
ctx.register_platform(
|
||||
name="feishu", label="Feishu / Lark", adapter_factory=_build_adapter,
|
||||
name="feishu", label="Feishu / Lark", adapter_factory=FeishuAdapter,
|
||||
check_fn=feishu_deps_present, ensure_deps_fn=check_feishu_requirements,
|
||||
is_connected=_is_connected, validate_config=_is_connected,
|
||||
required_env=["FEISHU_APP_ID", "FEISHU_APP_SECRET"],
|
||||
|
||||
@@ -24,7 +24,9 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from agent.secret_scope import is_multiplex_active
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
|
||||
from .cards import card_spec_to_cards_v2, format_message as _format_message
|
||||
|
||||
@@ -1532,32 +1534,29 @@ def _is_connected(config: PlatformConfig) -> bool:
|
||||
return bool(getattr(config, "enabled", False)) and _validate_config(config)
|
||||
|
||||
|
||||
_ENV_SEED_KEYS = (
|
||||
("http_events_audience", "GOOGLE_CHAT_HTTP_EVENTS_AUDIENCE"),
|
||||
("http_events_service_account_email", "GOOGLE_CHAT_HTTP_EVENTS_SERVICE_ACCOUNT_EMAIL"),
|
||||
("max_messages", "GOOGLE_CHAT_MAX_MESSAGES"), ("max_bytes", "GOOGLE_CHAT_MAX_BYTES"),
|
||||
("bootstrap_spaces", "GOOGLE_CHAT_BOOTSTRAP_SPACES"), ("debug_raw", "GOOGLE_CHAT_DEBUG_RAW"),
|
||||
_ENV_SEED_KEYS = ( # (env var, extra key, conv) for seed_extra_from_env
|
||||
("GOOGLE_CHAT_HTTP_EVENTS_AUDIENCE", "http_events_audience", None),
|
||||
("GOOGLE_CHAT_HTTP_EVENTS_SERVICE_ACCOUNT_EMAIL", "http_events_service_account_email", None),
|
||||
("GOOGLE_CHAT_MAX_MESSAGES", "max_messages", None), ("GOOGLE_CHAT_MAX_BYTES", "max_bytes", None),
|
||||
("GOOGLE_CHAT_BOOTSTRAP_SPACES", "bootstrap_spaces", None), ("GOOGLE_CHAT_DEBUG_RAW", "debug_raw", None),
|
||||
)
|
||||
|
||||
|
||||
def _env_enablement() -> Optional[Dict[str, Any]]:
|
||||
"""Seed ``PlatformConfig.extra`` from env during ``_apply_env_overrides`` (before the
|
||||
adapter exists, so ``gateway status`` reflects env-only config). None when the minimum
|
||||
inbound settings are absent; ``home_channel`` becomes a ``HomeChannel`` in the core hook."""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env before the adapter exists
|
||||
(so ``gateway status`` reflects env-only config); ``None`` when the minimum inbound settings are absent."""
|
||||
if not _env_inbound_configured():
|
||||
return None
|
||||
project, subscription, http_events_url = _env_inbound_settings()
|
||||
values = [("project_id", project), ("subscription_name", subscription), ("http_events_url", http_events_url)]
|
||||
values += [(extra_name, _get_scoped_secret(env)) for extra_name, env in _ENV_SEED_KEYS]
|
||||
values.append(("service_account_json", _get_scoped_secret("GOOGLE_CHAT_SERVICE_ACCOUNT_JSON")
|
||||
or _get_scoped_secret("GOOGLE_APPLICATION_CREDENTIALS")))
|
||||
seed: Dict[str, Any] = {extra_name: value for extra_name, value in values if value}
|
||||
home = _get_scoped_secret("GOOGLE_CHAT_HOME_CHANNEL")
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("GOOGLE_CHAT_HOME_CHANNEL_NAME", "Home")}
|
||||
values = [("project_id", project), ("subscription_name", subscription), ("http_events_url", http_events_url),
|
||||
("service_account_json", _get_scoped_secret("GOOGLE_CHAT_SERVICE_ACCOUNT_JSON")
|
||||
or _get_scoped_secret("GOOGLE_APPLICATION_CREDENTIALS"))]
|
||||
seed = {extra_name: value for extra_name, value in values if value}
|
||||
seed.update(_seed_extra_from_env(_ENV_SEED_KEYS, home_env="GOOGLE_CHAT_HOME_CHANNEL"))
|
||||
return seed
|
||||
|
||||
|
||||
|
||||
_SETUP_WALKTHROUGH = """Google Chat needs a GCP project, a Pub/Sub topic + subscription,
|
||||
and a Service Account with Pub/Sub Subscriber on the subscription.
|
||||
Walkthrough:
|
||||
|
||||
@@ -6,7 +6,6 @@ Requires aiohttp, HASS_TOKEN (Long-Lived Access Token) and HASS_URL (default htt
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
@@ -22,7 +21,9 @@ except ImportError:
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
env_is_connected as _env_is_connected, get_scoped_secret as _get_scoped_secret, send_error
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -337,11 +338,8 @@ async def _standalone_send(
|
||||
return send_error(f"Home Assistant send failed: {e}")
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
"""Connected when ``HASS_TOKEN`` is set; read via ``hermes_cli.gateway.get_env_value`` at call
|
||||
time so tests patching ``gateway_mod.get_env_value`` can suppress ambient env vars."""
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return bool((gateway_mod.get_env_value("HASS_TOKEN") or "").strip())
|
||||
_is_connected = _env_is_connected("HASS_TOKEN")
|
||||
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
|
||||
@@ -15,7 +15,9 @@ import ssl
|
||||
import time
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from gateway.platforms._shared import coerce_port, get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
coerce_port, get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.helpers import cancel_task
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
@@ -412,26 +414,21 @@ def is_connected(config) -> bool:
|
||||
|
||||
|
||||
def _env_enablement() -> dict | None:
|
||||
"""Seed ``PlatformConfig.extra`` from env vars BEFORE adapter construction; ``None`` when IRC isn't
|
||||
minimally configured (caller skips auto-enabling). ``home_channel`` becomes a ``HomeChannel``."""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env BEFORE adapter construction;
|
||||
``None`` when IRC isn't minimally configured. Passwords also live in extra for back-compat with
|
||||
config.yaml users; env wins at construct time. Home channel defaults to IRC_CHANNEL so cron
|
||||
``deliver=irc`` has a target without extra config."""
|
||||
server = _get_scoped_secret("IRC_SERVER", "").strip()
|
||||
channel = _get_scoped_secret("IRC_CHANNEL", "").strip()
|
||||
if not (server and channel):
|
||||
return None
|
||||
seed: dict = {"server": server, "channel": channel}
|
||||
for env, key, conv in (("IRC_PORT", "port", int), ("IRC_NICKNAME", "nickname", str),
|
||||
("IRC_USE_TLS", "use_tls", lambda v: v.lower() in _TRUTHY)):
|
||||
if raw := _get_scoped_secret(env, "").strip():
|
||||
with contextlib.suppress(ValueError): # non-numeric IRC_PORT is dropped, not fatal
|
||||
seed[key] = conv(raw)
|
||||
# Passwords also live in extra for back-compat with config.yaml users; env wins at construct time.
|
||||
for env, key in (("IRC_SERVER_PASSWORD", "server_password"), ("IRC_NICKSERV_PASSWORD", "nickserv_password")):
|
||||
if secret := _get_scoped_secret(env):
|
||||
seed[key] = secret
|
||||
# Home channel defaults to IRC_CHANNEL so cron ``deliver=irc`` has a target without extra config.
|
||||
if home := _get_scoped_secret("IRC_HOME_CHANNEL") or channel:
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("IRC_HOME_CHANNEL_NAME", home)}
|
||||
return seed
|
||||
seed = _seed_extra_from_env((
|
||||
("IRC_PORT", "port", int), ("IRC_NICKNAME", "nickname", None),
|
||||
("IRC_USE_TLS", "use_tls", lambda v: v.lower() in _TRUTHY),
|
||||
("IRC_SERVER_PASSWORD", "server_password", None), ("IRC_NICKSERV_PASSWORD", "nickserv_password", None),
|
||||
), home_env="IRC_HOME_CHANNEL", home_default=channel)
|
||||
return {"server": server, "channel": channel, **seed}
|
||||
|
||||
|
||||
|
||||
def _strip_irc_control_chars(text: str) -> str:
|
||||
|
||||
@@ -35,7 +35,9 @@ from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
||||
from urllib.parse import quote as _urlquote
|
||||
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
from gateway.platforms.base import (
|
||||
gateway_trust_env, BasePlatformAdapter, SendResult,
|
||||
cache_audio_from_bytes_async, cache_document_from_bytes_async, cache_image_from_bytes_async,
|
||||
@@ -360,7 +362,7 @@ _OUTBOUND_MEDIA = {
|
||||
_INBOUND_MEDIA_EXT = {"image": ".jpg", "audio": ".m4a", "video": ".mp4", "file": ".bin"}
|
||||
_INBOUND_AV_CACHERS = {"audio": cache_audio_from_bytes_async, "video": cache_video_from_bytes_async}
|
||||
_LIFECYCLE_EVENTS = frozenset({"follow", "unfollow", "join", "leave"})
|
||||
_ENV_SEED_KEYS = (("LINE_HOST", "host"), ("LINE_PUBLIC_URL", "public_url"), ("LINE_HOME_CHANNEL", "home_channel"))
|
||||
_ENV_SEED_KEYS = (("LINE_PORT", "port", int), ("LINE_HOST", "host", None), ("LINE_PUBLIC_URL", "public_url", None))
|
||||
|
||||
|
||||
class LineAdapter(BasePlatformAdapter):
|
||||
@@ -910,15 +912,11 @@ def is_connected(config) -> bool:
|
||||
|
||||
|
||||
def _env_enablement() -> Optional[Dict[str, Any]]:
|
||||
"""Seed PlatformConfig.extra from env-only setups so ``hermes status`` sees them."""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from env-only setups so ``hermes status`` sees them."""
|
||||
if not _env_credentials_present():
|
||||
return None
|
||||
seeded: Dict[str, Any] = {}
|
||||
if _get_scoped_secret("LINE_PORT"):
|
||||
with contextlib.suppress(ValueError):
|
||||
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
|
||||
return _seed_extra_from_env(_ENV_SEED_KEYS, home_env="LINE_HOME_CHANNEL")
|
||||
|
||||
|
||||
|
||||
async def _standalone_send(
|
||||
|
||||
@@ -37,8 +37,10 @@ from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Set
|
||||
|
||||
from agent.secret_scope import UnscopedSecretError, get_secret
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error, yaml_env_setter as _yaml_env_setter
|
||||
from agent.secret_scope import get_secret
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, get_scoped_secret as _get_scoped_secret, send_error
|
||||
)
|
||||
|
||||
try:
|
||||
from mautrix.types import (
|
||||
@@ -479,7 +481,7 @@ def _extra_csv_set(config, key: str, env_name: str) -> Set[str]:
|
||||
raw = config.extra.get(key)
|
||||
if raw is None:
|
||||
# Scoped read: under multiplex os.environ is the DEFAULT profile's room/user list.
|
||||
raw = _startup_env_secret(env_name)
|
||||
raw = _get_scoped_secret(env_name, "").strip()
|
||||
return _csv_set(raw)
|
||||
|
||||
|
||||
@@ -550,15 +552,9 @@ def _handle_generated_matrix_recovery_key(mxid: str, recovery_key: str) -> None:
|
||||
|
||||
|
||||
def _scoped_recovery_key() -> str:
|
||||
"""MATRIX_RECOVERY_KEY via the profile-scoped secret store (see _startup_env_secret): a bare
|
||||
os.getenv under multiplex resolves the default profile's key and verification fails with
|
||||
"Key MAC does not match".
|
||||
|
||||
We read through :func:`get_secret`, which is scope-aware. An *unscoped* read under multiplex (e.g. the
|
||||
default-profile startup loop) raises ``UnscopedSecretError``; in that context ``os.environ`` is that
|
||||
profile's own value, so we fall back to it — mirroring the established Slack app-token pattern (#59739).
|
||||
"""
|
||||
return _startup_env_secret("MATRIX_RECOVERY_KEY")
|
||||
"""MATRIX_RECOVERY_KEY via the profile-scoped reader: a bare os.getenv under multiplex resolves
|
||||
the default profile's key and verification fails with "Key MAC does not match"."""
|
||||
return _get_scoped_secret("MATRIX_RECOVERY_KEY", "").strip()
|
||||
|
||||
|
||||
# --- LaTeX math ($...$, $$...$$) -> Element data-mx-maths markup ---
|
||||
@@ -643,18 +639,6 @@ def _pre_sanitize_matrix_markdown(text: str) -> str:
|
||||
"", result)
|
||||
|
||||
|
||||
def _startup_env_secret(name: str) -> str:
|
||||
"""Scope-aware credential read: a scoped miss is empty (never borrow the process env);
|
||||
only an UNSCOPED read (default-profile startup loop) falls back to os.environ.
|
||||
|
||||
See #59739.
|
||||
"""
|
||||
try:
|
||||
return (get_secret(name) or "").strip()
|
||||
except UnscopedSecretError:
|
||||
return os.getenv(name, "").strip()
|
||||
|
||||
|
||||
def matrix_deps_present() -> bool:
|
||||
"""PASSIVE registry ``check_fn`` — must never install; ``ensure_matrix_deps`` is the installer.
|
||||
|
||||
@@ -671,9 +655,9 @@ def matrix_deps_present() -> bool:
|
||||
|
||||
def check_matrix_requirements() -> bool:
|
||||
"""Credentials + deps answer for setup/status callers (credentials must NOT gate the installer)."""
|
||||
token = _startup_env_secret("MATRIX_ACCESS_TOKEN")
|
||||
password = _startup_env_secret("MATRIX_PASSWORD")
|
||||
homeserver = _startup_env_secret("MATRIX_HOMESERVER")
|
||||
token = _get_scoped_secret("MATRIX_ACCESS_TOKEN", "").strip()
|
||||
password = _get_scoped_secret("MATRIX_PASSWORD", "").strip()
|
||||
homeserver = _get_scoped_secret("MATRIX_HOMESERVER", "").strip()
|
||||
if not token and not password:
|
||||
logger.debug("Matrix: neither MATRIX_ACCESS_TOKEN nor MATRIX_PASSWORD set")
|
||||
return False
|
||||
@@ -799,13 +783,13 @@ class MatrixAdapter(BasePlatformAdapter):
|
||||
# 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 _startup_env_secret("MATRIX_USER_ID")
|
||||
self._password: str = config.extra.get("password", "") or _startup_env_secret("MATRIX_PASSWORD")
|
||||
self._homeserver: str = (config.extra.get("homeserver", "") or _get_scoped_secret("MATRIX_HOMESERVER", "").strip()).rstrip("/")
|
||||
self._access_token: str = config.token or _get_scoped_secret("MATRIX_ACCESS_TOKEN", "").strip()
|
||||
self._user_id: str = config.extra.get("user_id", "") or _get_scoped_secret("MATRIX_USER_ID", "").strip()
|
||||
self._password: str = config.extra.get("password", "") or _get_scoped_secret("MATRIX_PASSWORD", "").strip()
|
||||
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 _startup_env_secret("MATRIX_DEVICE_ID")
|
||||
self._device_id: str = config.extra.get("device_id", "") or _get_scoped_secret("MATRIX_DEVICE_ID", "").strip()
|
||||
self._device_id_unverified: bool = False
|
||||
self._client: Any = None # mautrix.client.Client
|
||||
self._crypto_db: Any = None # mautrix.util.async_db.Database
|
||||
@@ -864,10 +848,10 @@ class MatrixAdapter(BasePlatformAdapter):
|
||||
self._choice_picker_prompts_by_event: Dict[str, _MatrixPickerPrompt] = {}
|
||||
# Authz lists via the scoped reader: under multiplex os.environ is the DEFAULT profile's
|
||||
# allowlist, which must not decide who approves tool calls on a secondary bot.
|
||||
self._allowed_user_ids: Set[str] = _csv_set(_startup_env_secret("MATRIX_ALLOWED_USERS"))
|
||||
self._allowed_user_ids: Set[str] = _csv_set(_get_scoped_secret("MATRIX_ALLOWED_USERS", "").strip())
|
||||
self._allowed_room_ids: Set[str] = set(self._allowed_rooms)
|
||||
self._ignored_user_patterns: list[re.Pattern[str]] = []
|
||||
for pattern in (p.strip() for p in _startup_env_secret("MATRIX_IGNORE_USER_PATTERNS").split(",") if p.strip()):
|
||||
for pattern in (p.strip() for p in _get_scoped_secret("MATRIX_IGNORE_USER_PATTERNS", "").strip().split(",") if p.strip()):
|
||||
try:
|
||||
self._ignored_user_patterns.append(re.compile(pattern))
|
||||
except re.error as exc:
|
||||
@@ -2394,7 +2378,7 @@ class MatrixAdapter(BasePlatformAdapter):
|
||||
def _is_authorized_user(self, user_id: str) -> bool:
|
||||
"""GATEWAY_ALLOW_ALL_USERS, or membership in MATRIX_ALLOWED_USERS."""
|
||||
# Scoped read — the DEFAULT profile's os.environ opt-in must not authorize on a secondary bot.
|
||||
return _startup_env_secret("GATEWAY_ALLOW_ALL_USERS").lower() in ("true", "1", "yes") or bool(
|
||||
return _get_scoped_secret("GATEWAY_ALLOW_ALL_USERS", "").strip().lower() in ("true", "1", "yes") or bool(
|
||||
self._allowed_user_ids and user_id in self._allowed_user_ids)
|
||||
|
||||
async def _validate_matrix_prompt_reactor(
|
||||
@@ -2984,38 +2968,21 @@ def interactive_setup() -> None:
|
||||
print_info("Home room cleared.")
|
||||
|
||||
|
||||
_YAML_LOWER_KEYS = (
|
||||
("require_mention", "MATRIX_REQUIRE_MENTION"), ("process_notices", "MATRIX_PROCESS_NOTICES"),
|
||||
("session_scope", "MATRIX_SESSION_SCOPE"), ("auto_thread", "MATRIX_AUTO_THREAD"),
|
||||
("dm_mention_threads", "MATRIX_DM_MENTION_THREADS"))
|
||||
_YAML_LIST_KEYS = (
|
||||
("allowed_users", "MATRIX_ALLOWED_USERS"), ("free_response_rooms", "MATRIX_FREE_RESPONSE_ROOMS"),
|
||||
("allowed_rooms", "MATRIX_ALLOWED_ROOMS"), ("ignore_user_patterns", "MATRIX_IGNORE_USER_PATTERNS"))
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
|
||||
("require_mention", "MATRIX_REQUIRE_MENTION", "lower"), ("process_notices", "MATRIX_PROCESS_NOTICES", "lower"),
|
||||
("session_scope", "MATRIX_SESSION_SCOPE", "lower"), ("auto_thread", "MATRIX_AUTO_THREAD", "lower"),
|
||||
("dm_mention_threads", "MATRIX_DM_MENTION_THREADS", "lower"),
|
||||
("allowed_users", "MATRIX_ALLOWED_USERS", "csv"), ("free_response_rooms", "MATRIX_FREE_RESPONSE_ROOMS", "csv"),
|
||||
("allowed_rooms", "MATRIX_ALLOWED_ROOMS", "csv"), ("ignore_user_patterns", "MATRIX_IGNORE_USER_PATTERNS", "csv"),
|
||||
("max_message_length", "MATRIX_MAX_MESSAGE_LENGTH", "str"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, matrix_cfg: dict) -> dict | None:
|
||||
"""apply_yaml_config_fn: config.yaml matrix: keys → MATRIX_* env (env wins) + ``PlatformConfig.extra``.
|
||||
Lowercased flags apply whenever the key is present (None still writes "none"); list-valued keys skip None.
|
||||
"""``apply_yaml_config_fn`` (#24849): config.yaml matrix: keys → MATRIX_* env (env wins; skipped under a
|
||||
multiplexed secondary profile's scope) + ``PlatformConfig.extra`` (extra-first readers)."""
|
||||
return _apply_yaml_bridge(matrix_cfg, _YAML_BRIDGE)
|
||||
|
||||
Implements the apply_yaml_config_fn contract (#24849). Mirrors the legacy matrix_cfg block from
|
||||
gateway/config.py::load_gateway_config(). The env write is skipped under a multiplexed secondary
|
||||
profile's scope; the seeded ``extra`` is what its adapter reads (extra-first readers).
|
||||
"""
|
||||
_set_env = _yaml_env_setter()
|
||||
seeded: dict = {}
|
||||
for key, env_name in _YAML_LOWER_KEYS:
|
||||
if key in matrix_cfg:
|
||||
seeded[key] = matrix_cfg[key]
|
||||
_set_env(env_name, str(matrix_cfg[key]).lower())
|
||||
for key, env_name in _YAML_LIST_KEYS:
|
||||
value = matrix_cfg.get(key)
|
||||
if value is not None:
|
||||
seeded[key] = value
|
||||
_set_env(env_name, value)
|
||||
if "max_message_length" in matrix_cfg:
|
||||
seeded["max_message_length"] = matrix_cfg["max_message_length"]
|
||||
_set_env("MATRIX_MAX_MESSAGE_LENGTH", str(matrix_cfg["max_message_length"]))
|
||||
return seeded or None
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
@@ -3029,14 +2996,10 @@ def _is_connected(config) -> bool:
|
||||
return bool(str(homeserver).strip() and str(token).strip())
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
"""Factory wrapper that constructs MatrixAdapter from a PlatformConfig."""
|
||||
return MatrixAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
ctx.register_platform(
|
||||
name="matrix", label="Matrix", adapter_factory=_build_adapter, check_fn=matrix_deps_present,
|
||||
name="matrix", label="Matrix", adapter_factory=MatrixAdapter, check_fn=matrix_deps_present,
|
||||
ensure_deps_fn=ensure_matrix_deps, is_connected=_is_connected,
|
||||
required_env=["MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"], install_hint="pip install 'mautrix[encryption]'",
|
||||
setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="MATRIX_ALLOWED_USERS",
|
||||
|
||||
@@ -10,7 +10,6 @@ Environment variables:
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
@@ -25,7 +24,11 @@ from gateway.platforms.helpers import MessageDeduplicator
|
||||
from gateway.platforms.helpers import cancel_task
|
||||
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, profile_scoped as _profile_scoped_config_load, send_error
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, env_is_connected as _env_is_connected,
|
||||
extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret,
|
||||
send_error
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -59,10 +62,6 @@ def _channel_id_set(raw: Any) -> set:
|
||||
return {str(c).strip() for c in items if str(c).strip()}
|
||||
|
||||
|
||||
def _csv(value: Any) -> str:
|
||||
return ",".join(str(v) for v in value) if isinstance(value, list) else str(value)
|
||||
|
||||
|
||||
def _post_result(data: Dict[str, Any], error: str) -> SendResult:
|
||||
if not data or "id" not in data:
|
||||
return SendResult(success=False, error=error)
|
||||
@@ -492,23 +491,18 @@ class MattermostAdapter(BasePlatformAdapter):
|
||||
logger.info("Mattermost: WebSocket closed (%s)", kind)
|
||||
break
|
||||
|
||||
def _extra_or_env(self, key: str, env: str, default: str = "") -> Any:
|
||||
"""config.yaml ``mattermost.<key>`` (PlatformConfig.extra) first, env var fallback."""
|
||||
raw = self.config.extra.get(key) if self.config.extra else None
|
||||
return _get_scoped_secret(env, default) if raw is None else raw
|
||||
|
||||
def _apply_channel_gating(self, channel_id: str, message_text: str) -> Optional[str]:
|
||||
"""Mention-gate a non-DM post; return the cleaned text, or None to ignore it. allowed_channels is a
|
||||
whitelist checked first (@mentions elsewhere are ignored); require_mention (default true) is
|
||||
bypassed in free_response_channels."""
|
||||
allowed_channels = _channel_id_set(self._extra_or_env("allowed_channels", "MATTERMOST_ALLOWED_CHANNELS"))
|
||||
allowed_channels = _channel_id_set(_extra_or_secret(self.config.extra, "allowed_channels", "MATTERMOST_ALLOWED_CHANNELS"))
|
||||
if allowed_channels and channel_id not in allowed_channels:
|
||||
logger.debug("Mattermost: ignoring message in non-allowed channel: %s", channel_id)
|
||||
return None
|
||||
require_mention = str(self._extra_or_env("require_mention", "MATTERMOST_REQUIRE_MENTION", "true")
|
||||
require_mention = str(_extra_or_secret(self.config.extra, "require_mention", "MATTERMOST_REQUIRE_MENTION", "true")
|
||||
).lower() not in {"false", "0", "no"}
|
||||
free_channels = _channel_id_set(
|
||||
self._extra_or_env("free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS"))
|
||||
_extra_or_secret(self.config.extra, "free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS"))
|
||||
mention_patterns = [f"@{self._bot_username}", f"@{self._bot_user_id}"]
|
||||
has_mention = any(pattern.lower() in message_text.lower() for pattern in mention_patterns)
|
||||
if require_mention and channel_id not in free_channels and not has_mention:
|
||||
@@ -657,8 +651,8 @@ async def _standalone_send(pconfig, chat_id: str, message: str, *, thread_id: Op
|
||||
|
||||
def interactive_setup() -> None:
|
||||
"""Guide the user through Mattermost bot setup (URL + token, allowlist, home channel)."""
|
||||
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
|
||||
from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success
|
||||
from hermes_cli.config import remove_env_value, save_env_value
|
||||
from hermes_cli.cli_output import prompt, print_header, print_info, print_success
|
||||
from hermes_cli.setup_platforms import declines_reconfigure
|
||||
|
||||
def info(*lines: str) -> None:
|
||||
@@ -703,45 +697,22 @@ def interactive_setup() -> None:
|
||||
|
||||
# --- YAML → env config bridge (apply_yaml_config_fn) ---
|
||||
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, yaml value → env string); allowed_channels is a whitelist
|
||||
("require_mention", "MATTERMOST_REQUIRE_MENTION", lambda v: str(v).lower()),
|
||||
("free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS", _csv),
|
||||
("allowed_channels", "MATTERMOST_ALLOWED_CHANNELS", _csv))
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge; allowed_channels is a whitelist
|
||||
("require_mention", "MATTERMOST_REQUIRE_MENTION", "lower"),
|
||||
("free_response_channels", "MATTERMOST_FREE_RESPONSE_CHANNELS", "csv"),
|
||||
("allowed_channels", "MATTERMOST_ALLOWED_CHANNELS", "csv"))
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, mattermost_cfg: dict) -> dict | None:
|
||||
"""Translate ``config.yaml`` ``mattermost:`` keys into env vars + ``PlatformConfig.extra``.
|
||||
|
||||
Env vars win over YAML (writes guarded by ``not os.getenv``). Under a multiplexed secondary
|
||||
profile the env write is skipped (it would leak into every profile via ``os.environ``); the
|
||||
values are returned so the caller seeds this profile's ``extra``, which read sites check first.
|
||||
|
||||
Implements the ``apply_yaml_config_fn`` contract (#24836 / #25443). Mirrors the legacy
|
||||
``mattermost_cfg`` block that used to live in ``gateway/config.py::load_gateway_config()`` before this
|
||||
migration.
|
||||
"""
|
||||
skip_env_bridge = _profile_scoped_config_load()
|
||||
seeded: dict = {}
|
||||
for key, env, to_env in _YAML_BRIDGE:
|
||||
value = mattermost_cfg.get(key)
|
||||
if value is None and not (key == "require_mention" and key in mattermost_cfg):
|
||||
continue
|
||||
seeded[key] = value
|
||||
if not skip_env_bridge and not os.getenv(env):
|
||||
os.environ[env] = to_env(value)
|
||||
return seeded or None
|
||||
"""``apply_yaml_config_fn`` (#24836 / #25443): ``config.yaml`` ``mattermost:`` keys → env vars (env wins;
|
||||
skipped under a multiplexed secondary profile) + ``PlatformConfig.extra`` (extra-first readers)."""
|
||||
return _apply_yaml_bridge(mattermost_cfg, _YAML_BRIDGE)
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
"""Connected when BOTH MATTERMOST_TOKEN and MATTERMOST_URL are set (``get_env_value`` looked up at
|
||||
call time so tests patching ``gateway_mod.get_env_value`` can suppress ambient env vars)."""
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return bool(
|
||||
(gateway_mod.get_env_value("MATTERMOST_TOKEN") or "").strip()
|
||||
and (gateway_mod.get_env_value("MATTERMOST_URL") or "").strip())
|
||||
|
||||
_is_connected = _env_is_connected("MATTERMOST_TOKEN", "MATTERMOST_URL")
|
||||
|
||||
|
||||
# --- Plugin registration entry point ---
|
||||
|
||||
def register(ctx) -> None:
|
||||
"""Plugin entry point — called by the Hermes plugin system."""
|
||||
|
||||
@@ -29,6 +29,9 @@ from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms.helpers import MessageDeduplicator
|
||||
from gateway.platforms._shared import (
|
||||
extra_or_secret as _extra_or_secret, seed_extra_from_env as _seed_extra_from_env
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -92,13 +95,8 @@ def _response_message_id(resp) -> str:
|
||||
return uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
def _setting(extra: Dict[str, Any], key: str, env: str, default: str = "") -> str:
|
||||
"""config.yaml ``extra[key]`` wins over the env var ``env``."""
|
||||
return extra.get(key) or _get_scoped_secret(env, default)
|
||||
|
||||
|
||||
def _server_url(extra: Dict[str, Any]) -> str:
|
||||
return _setting(extra, "server", "NTFY_SERVER_URL", DEFAULT_SERVER).rstrip("/")
|
||||
return _extra_or_secret(extra, "server", "NTFY_SERVER_URL", DEFAULT_SERVER).rstrip("/")
|
||||
|
||||
|
||||
def check_requirements() -> bool:
|
||||
@@ -108,7 +106,7 @@ def check_requirements() -> bool:
|
||||
|
||||
def validate_config(config) -> bool:
|
||||
"""True when a topic is configured (config.yaml ``extra`` or env)."""
|
||||
return bool(_setting(getattr(config, "extra", {}) or {}, "topic", "NTFY_TOPIC"))
|
||||
return bool(_extra_or_secret(getattr(config, "extra", {}) or {}, "topic", "NTFY_TOPIC"))
|
||||
|
||||
|
||||
def is_connected(config) -> bool:
|
||||
@@ -125,9 +123,9 @@ class NtfyAdapter(BasePlatformAdapter):
|
||||
super().__init__(config=config, platform=Platform("ntfy"))
|
||||
extra = config.extra or {}
|
||||
self._server: str = _server_url(extra)
|
||||
self._topic: str = _setting(extra, "topic", "NTFY_TOPIC")
|
||||
self._publish_topic: str = _setting(extra, "publish_topic", "NTFY_PUBLISH_TOPIC") or self._topic
|
||||
self._token: str = _setting(extra, "token", "NTFY_TOKEN")
|
||||
self._topic: str = _extra_or_secret(extra, "topic", "NTFY_TOPIC")
|
||||
self._publish_topic: str = _extra_or_secret(extra, "publish_topic", "NTFY_PUBLISH_TOPIC") or self._topic
|
||||
self._token: str = _extra_or_secret(extra, "token", "NTFY_TOKEN")
|
||||
self._stream_task: Optional[asyncio.Task] = None
|
||||
self._http_client: Optional["httpx.AsyncClient"] = None
|
||||
self._dedup = MessageDeduplicator(max_size=DEDUP_MAX_SIZE, ttl_seconds=DEDUP_WINDOW_SECONDS)
|
||||
@@ -309,29 +307,17 @@ class NtfyAdapter(BasePlatformAdapter):
|
||||
|
||||
|
||||
def _env_enablement() -> dict | None:
|
||||
"""Seed ``PlatformConfig.extra`` from env vars during gateway config load.
|
||||
|
||||
Runs BEFORE adapter construction so ``gateway status`` reflects env-only
|
||||
setups without instantiating the HTTP client. ``None`` = not configured.
|
||||
The ``home_channel`` key is lifted by the core hook into a ``HomeChannel``
|
||||
on the ``PlatformConfig`` instead of being merged into ``extra``.
|
||||
"""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env before adapter
|
||||
construction; ``None`` when ``NTFY_TOPIC`` is unset."""
|
||||
topic = _get_scoped_secret("NTFY_TOPIC", "").strip()
|
||||
if not topic:
|
||||
return None
|
||||
seed: dict = {
|
||||
"topic": topic, "server": _get_scoped_secret("NTFY_SERVER_URL", DEFAULT_SERVER).rstrip("/")}
|
||||
for key, env in (("publish_topic", "NTFY_PUBLISH_TOPIC"), ("token", "NTFY_TOKEN")):
|
||||
value = _get_scoped_secret(env, "").strip()
|
||||
if value:
|
||||
seed[key] = value
|
||||
markdown = _get_scoped_secret("NTFY_MARKDOWN", "").strip().lower()
|
||||
if markdown:
|
||||
seed["markdown"] = markdown in _MARKDOWN_TRUTHY
|
||||
home = _get_scoped_secret("NTFY_HOME_CHANNEL", "").strip() or topic
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("NTFY_HOME_CHANNEL_NAME", home)}
|
||||
return seed
|
||||
seed = _seed_extra_from_env((
|
||||
("NTFY_SERVER_URL", "server", lambda v: v.rstrip("/")), ("NTFY_PUBLISH_TOPIC", "publish_topic", None),
|
||||
("NTFY_TOKEN", "token", None), ("NTFY_MARKDOWN", "markdown", lambda v: v.lower() in _MARKDOWN_TRUTHY),
|
||||
), home_env="NTFY_HOME_CHANNEL", home_default=topic)
|
||||
return {"topic": topic, "server": seed.pop("server", DEFAULT_SERVER), **seed}
|
||||
|
||||
|
||||
|
||||
async def _standalone_send(
|
||||
@@ -353,7 +339,7 @@ async def _standalone_send(
|
||||
or extra.get("topic") or _get_scoped_secret("NTFY_TOPIC", "").strip())
|
||||
if not publish_topic:
|
||||
return send_error("ntfy standalone send: NTFY_TOPIC not configured")
|
||||
token = _setting(extra, "token", "NTFY_TOKEN")
|
||||
token = _extra_or_secret(extra, "token", "NTFY_TOKEN")
|
||||
markdown_env = _get_scoped_secret("NTFY_MARKDOWN", "").strip().lower()
|
||||
markdown = bool(extra.get("markdown")) or markdown_env in _MARKDOWN_TRUTHY
|
||||
headers = _publish_headers(token, markdown, auth_first=False)
|
||||
|
||||
@@ -37,7 +37,10 @@ else:
|
||||
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms._shared import coerce_port as _coerce_port
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret,
|
||||
seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms.helpers import compile_mention_patterns, strip_markdown
|
||||
@@ -268,16 +271,13 @@ def is_connected(cfg: PlatformConfig) -> bool:
|
||||
|
||||
|
||||
def _env_enablement() -> Optional[dict]:
|
||||
"""Seed PlatformConfig.extra from env so env-only setups appear in status
|
||||
(``home_channel`` becomes a ``HomeChannel`` via the core plugin hook)."""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` so env-only setups appear in status."""
|
||||
project_id, project_secret = load_project_credentials()
|
||||
if not (project_id and project_secret):
|
||||
return None
|
||||
seed: dict = {"project_id": project_id, "project_secret": project_secret}
|
||||
home = _get_scoped_secret("PHOTON_HOME_CHANNEL", "").strip()
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("PHOTON_HOME_CHANNEL_NAME", "Home")}
|
||||
return seed
|
||||
return {"project_id": project_id, "project_secret": project_secret,
|
||||
**_seed_extra_from_env((), home_env="PHOTON_HOME_CHANNEL")}
|
||||
|
||||
|
||||
|
||||
def _markdown_enabled() -> bool:
|
||||
@@ -468,11 +468,8 @@ class PhotonAdapter(BasePlatformAdapter):
|
||||
# respawns only when the sidecar's HTTP loop hangs; 10-min interval because shared
|
||||
# lines are quiet for hours. Config key wins, then env; None-aware so 0 disables it.
|
||||
def _setting(key: str, env: str, default: Any, cast: Callable[[Any], Any]) -> Any:
|
||||
value = extra.get(key)
|
||||
if value is None:
|
||||
value = _get_scoped_secret(env)
|
||||
try:
|
||||
return cast(value)
|
||||
return cast(_extra_or_secret(extra, key, env, None))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
self._probe_interval = _setting("probe_interval_seconds", "PHOTON_PROBE_INTERVAL_SECONDS", 600.0, float)
|
||||
|
||||
@@ -24,7 +24,9 @@ from typing import Any, Dict, List, Optional
|
||||
|
||||
from urllib.parse import unquote
|
||||
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult, cache_image_from_url
|
||||
from gateway.platforms.helpers import cancel_task
|
||||
@@ -586,20 +588,17 @@ def is_connected(config) -> bool:
|
||||
|
||||
|
||||
def _env_enablement() -> Optional[dict]:
|
||||
"""Seed ``PlatformConfig.extra`` from env BEFORE adapter construction so ``gateway status``
|
||||
reflects env-only setups. ``None`` when not minimally configured; ``home_channel`` becomes
|
||||
a ``HomeChannel`` via the core hook."""
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env BEFORE adapter
|
||||
construction; ``None`` when ``SIMPLEX_WS_URL`` is unset."""
|
||||
ws_url = _get_scoped_secret("SIMPLEX_WS_URL", "").strip()
|
||||
if not ws_url:
|
||||
return None
|
||||
seed: dict = {"ws_url": ws_url}
|
||||
if auto_accept := _get_scoped_secret("SIMPLEX_AUTO_ACCEPT", "").strip().lower():
|
||||
seed["auto_accept"] = auto_accept not in {"0", "false", "no"}
|
||||
if group_allowed := _get_scoped_secret("SIMPLEX_GROUP_ALLOWED", "").strip():
|
||||
seed["group_allowed"] = group_allowed
|
||||
if home := _get_scoped_secret("SIMPLEX_HOME_CHANNEL", "").strip():
|
||||
seed["home_channel"] = {"chat_id": home, "name": _get_scoped_secret("SIMPLEX_HOME_CHANNEL_NAME", "").strip() or home}
|
||||
return seed
|
||||
seed = _seed_extra_from_env((
|
||||
("SIMPLEX_AUTO_ACCEPT", "auto_accept", lambda v: v.lower() not in {"0", "false", "no"}),
|
||||
("SIMPLEX_GROUP_ALLOWED", "group_allowed", None),
|
||||
), home_env="SIMPLEX_HOME_CHANNEL")
|
||||
return {"ws_url": ws_url, **seed}
|
||||
|
||||
|
||||
|
||||
async def _standalone_send(
|
||||
|
||||
@@ -33,10 +33,14 @@ from pathlib import Path as _Path
|
||||
sys.path.insert(0, str(_Path(__file__).resolve().parents[3]))
|
||||
|
||||
from agent.retry_utils import parse_retry_after_seconds
|
||||
from agent.secret_scope import UnscopedSecretError, get_secret
|
||||
from agent.secret_scope import get_secret
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, env_is_connected as _env_is_connected,
|
||||
extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret,
|
||||
platform_gate_env as _scoped_gate_env, send_error
|
||||
)
|
||||
from gateway.platforms.helpers import MessageDeduplicator
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error, yaml_env_setter as _yaml_env_setter
|
||||
from gateway.platforms.base import (
|
||||
gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt,
|
||||
SendResult, SUPPORTED_DOCUMENT_TYPES, SUPPORTED_VIDEO_TYPES, _TEXT_INJECT_EXTENSIONS,
|
||||
@@ -1653,17 +1657,8 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
self._set_fatal_error("missing_dependency", "slack-bolt not installed", retryable=False)
|
||||
return False
|
||||
raw_token = self.config.token
|
||||
# Scoped secret is authoritative; only an UNSCOPED read falls back to
|
||||
# process env, else a secondary profile inherits the default's app.
|
||||
try:
|
||||
# Multiplex: profile secrets live in the secret scope, not process os.environ. When a scope is
|
||||
# installed (secondary-profile connect), it is AUTHORITATIVE — do not fall through to os.getenv,
|
||||
# or a secondary profile missing SLACK_APP_TOKEN silently inherits the default profile's Socket
|
||||
# Mode app (#59739). Only an UNSCOPED read under multiplex (default-profile startup loop,
|
||||
# background reconnect rebuild) falls back to process env, which is that profile's own.
|
||||
app_token = get_secret("SLACK_APP_TOKEN")
|
||||
except UnscopedSecretError:
|
||||
app_token = os.getenv("SLACK_APP_TOKEN")
|
||||
# Scoped read: a secondary profile missing SLACK_APP_TOKEN must not inherit the default's app (#59739).
|
||||
app_token = _get_scoped_secret("SLACK_APP_TOKEN")
|
||||
for env_name, value in (("SLACK_BOT_TOKEN", raw_token), ("SLACK_APP_TOKEN", app_token)):
|
||||
if not value:
|
||||
self._fatal_missing_env(env_name)
|
||||
@@ -5155,7 +5150,7 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
normalized_user_id, exc_info=True)
|
||||
# Env-only fallback. Per-profile accessor: under multiplex a scoped miss
|
||||
# returns "" rather than leaking the DEFAULT profile's os.environ allowlist.
|
||||
from gateway.authz_mixin import _platform_gate_env as _env
|
||||
_env = _scoped_gate_env
|
||||
if _env("SLACK_ALLOW_ALL_USERS").lower() in {"true", "1", "yes"}:
|
||||
return True
|
||||
allowed_ids = {
|
||||
@@ -5968,9 +5963,7 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
|
||||
def _extra_or_env_flag(self, key: str, env_var: str, *, strip: bool = False) -> bool:
|
||||
"""Opt-in boolean: ``config.extra[key]`` wins, else ``env_var`` (default false)."""
|
||||
configured = self.config.extra.get(key)
|
||||
if configured is None:
|
||||
configured = _get_scoped_secret(env_var, "false")
|
||||
configured = _extra_or_secret(self.config.extra, key, env_var, "false")
|
||||
if isinstance(configured, str):
|
||||
if strip:
|
||||
configured = configured.strip()
|
||||
@@ -6004,9 +5997,7 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
self, key: str, env_var: str, *, coerce_scalar: bool = False) -> set:
|
||||
"""Channel-ID set from ``config.extra[key]`` (list or CSV) else ``env_var`` CSV.
|
||||
``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 = _get_scoped_secret(env_var, "")
|
||||
raw = _extra_or_secret(self.config.extra, key, env_var, "")
|
||||
if isinstance(raw, list):
|
||||
return {str(part).strip() for part in raw if str(part).strip()}
|
||||
if coerce_scalar:
|
||||
@@ -6069,7 +6060,7 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
|
||||
|
||||
# ── Plugin entry point + hooks (register, _standalone_send, interactive_setup,
|
||||
# _apply_yaml_config, _is_connected, _build_adapter) ──────────────────────────
|
||||
# _apply_yaml_config, _is_connected) ──────────────────────────
|
||||
|
||||
|
||||
# Standalone-send cache: user ID -> DM conversation ID, keyed "{token}:{user_id}" (multi-workspace).
|
||||
@@ -6077,7 +6068,7 @@ class SlackAdapter(BasePlatformAdapter):
|
||||
# #3823) Everything below this line was added when the Slack adapter moved from
|
||||
# ``gateway/platforms/slack.py`` into this bundled plugin. It mirrors the Discord migration (PR #24356)
|
||||
# exactly: a ``register(ctx)`` entry point plus the hook implementations (``_standalone_send``,
|
||||
# ``interactive_setup``, ``_apply_yaml_config``, ``_is_connected``, ``_build_adapter``) that replace the
|
||||
# ``interactive_setup``, ``_apply_yaml_config``, ``_is_connected``) that replace the
|
||||
# per-platform core touchpoints (the ``Platform.SLACK`` elif in ``gateway/run.py``, the ``slack_cfg``
|
||||
# YAML→env block in ``gateway/config.py``, the ``_setup_slack`` wizard + ``_PLATFORMS["slack"]`` static dict
|
||||
# in ``hermes_cli/{setup,gateway}.py``, and the ``_send_slack`` dispatch in ``tools/send_message_tool.py``).
|
||||
@@ -6418,7 +6409,7 @@ def _write_slack_manifest_and_instruct() -> None:
|
||||
def interactive_setup() -> None:
|
||||
"""Guide the user through Slack bot setup (manifest, tokens, allowlist, home channel).
|
||||
CLI helpers are lazy-imported to keep the plugin's import surface small."""
|
||||
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
|
||||
from hermes_cli.config import remove_env_value, save_env_value
|
||||
from hermes_cli.cli_output import (
|
||||
prompt, prompt_yes_no, print_header, print_info, print_success, print_warning)
|
||||
from hermes_cli.setup_platforms import declines_reconfigure
|
||||
@@ -6472,55 +6463,27 @@ def interactive_setup() -> None:
|
||||
print_info("Home channel cleared.")
|
||||
|
||||
|
||||
_YAML_BOOL_KEYS = (
|
||||
("require_mention", "SLACK_REQUIRE_MENTION"), ("strict_mention", "SLACK_STRICT_MENTION"),
|
||||
("ignore_other_user_mentions", "SLACK_IGNORE_OTHER_USER_MENTIONS"),
|
||||
("thread_require_mention", "SLACK_THREAD_REQUIRE_MENTION"), ("allow_bots", "SLACK_ALLOW_BOTS"),
|
||||
("reactions", "SLACK_REACTIONS"), ("disable_dms", "SLACK_DISABLE_DMS"))
|
||||
# (yaml key, env var, list-ish types joined with ","); str(value) when not a list.
|
||||
_YAML_LIST_KEYS = (
|
||||
("free_response_channels", "SLACK_FREE_RESPONSE_CHANNELS", list),
|
||||
("require_mention_channels", "SLACK_REQUIRE_MENTION_CHANNELS", list),
|
||||
("reaction_triggers", "SLACK_REACTION_TRIGGERS", (list, tuple, set)),
|
||||
("reaction_trigger_target", "SLACK_REACTION_TRIGGER_TARGET", ()),
|
||||
("allowed_channels", "SLACK_ALLOWED_CHANNELS", list),
|
||||
("ignored_channels", "SLACK_IGNORED_CHANNELS", list))
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
|
||||
("require_mention", "SLACK_REQUIRE_MENTION", "lower"), ("strict_mention", "SLACK_STRICT_MENTION", "lower"),
|
||||
("ignore_other_user_mentions", "SLACK_IGNORE_OTHER_USER_MENTIONS", "lower"),
|
||||
("thread_require_mention", "SLACK_THREAD_REQUIRE_MENTION", "lower"), ("allow_bots", "SLACK_ALLOW_BOTS", "lower"),
|
||||
("reactions", "SLACK_REACTIONS", "lower"), ("disable_dms", "SLACK_DISABLE_DMS", "lower"),
|
||||
("free_response_channels", "SLACK_FREE_RESPONSE_CHANNELS", "csv"),
|
||||
("require_mention_channels", "SLACK_REQUIRE_MENTION_CHANNELS", "csv"),
|
||||
("reaction_triggers", "SLACK_REACTION_TRIGGERS", "csv"), ("reaction_trigger_target", "SLACK_REACTION_TRIGGER_TARGET", "str"),
|
||||
("allowed_channels", "SLACK_ALLOWED_CHANNELS", "csv"), ("ignored_channels", "SLACK_IGNORED_CHANNELS", "csv"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, slack_cfg: dict) -> dict | None:
|
||||
"""``apply_yaml_config_fn`` hook: ``slack:`` YAML keys → ``SLACK_*`` env vars (explicit env wins) and
|
||||
``PlatformConfig.extra`` (extra-first readers; the env write is skipped under a multiplexed
|
||||
secondary profile's scope so its policy never becomes the default profile's).
|
||||
|
||||
Implements the ``apply_yaml_config_fn`` contract (#24849). Mirrors the legacy ``slack_cfg`` block that
|
||||
used to live in ``gateway/config.py::load_gateway_config()`` before this migration.
|
||||
"""
|
||||
_set_env = _yaml_env_setter()
|
||||
seeded: dict = {}
|
||||
for key, env in _YAML_BOOL_KEYS:
|
||||
if key in slack_cfg:
|
||||
seeded[key] = slack_cfg[key] # original type: the shared-key loop already seeded bools as bools
|
||||
_set_env(env, str(slack_cfg[key]).lower())
|
||||
for key, env, list_types in _YAML_LIST_KEYS:
|
||||
val = slack_cfg.get(key)
|
||||
if val is not None:
|
||||
seeded[key] = val
|
||||
if list_types and isinstance(val, list_types):
|
||||
val = ",".join(str(v) for v in val)
|
||||
_set_env(env, str(val))
|
||||
return seeded or None
|
||||
"""``apply_yaml_config_fn`` (#24849): ``slack:`` YAML keys → ``SLACK_*`` env (explicit env wins; skipped
|
||||
under a multiplexed secondary profile's scope) + ``PlatformConfig.extra`` (extra-first readers)."""
|
||||
return _apply_yaml_bridge(slack_cfg, _YAML_BRIDGE)
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
"""Connected when SLACK_BOT_TOKEN is set. Resolved through ``gateway_mod`` at call
|
||||
time (not a bound import) so tests patching ``get_env_value`` take effect."""
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return bool((gateway_mod.get_env_value("SLACK_BOT_TOKEN") or "").strip())
|
||||
|
||||
_is_connected = _env_is_connected("SLACK_BOT_TOKEN")
|
||||
|
||||
def _build_adapter(config):
|
||||
"""Factory wrapper that constructs SlackAdapter from a PlatformConfig."""
|
||||
return SlackAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
@@ -6528,7 +6491,7 @@ def register(ctx) -> None:
|
||||
ctx.register_platform(
|
||||
name="slack",
|
||||
label="Slack",
|
||||
adapter_factory=_build_adapter,
|
||||
adapter_factory=SlackAdapter,
|
||||
check_fn=slack_deps_present,
|
||||
ensure_deps_fn=check_slack_requirements,
|
||||
is_connected=_is_connected,
|
||||
|
||||
@@ -16,7 +16,6 @@ import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import urllib.parse
|
||||
from typing import Any, Dict, Optional
|
||||
@@ -25,7 +24,9 @@ from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms.helpers import redact_phone, strip_markdown
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
env_is_connected as _env_is_connected, get_scoped_secret as _get_scoped_secret, send_error
|
||||
)
|
||||
|
||||
try:
|
||||
import aiohttp
|
||||
@@ -322,10 +323,8 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
|
||||
return send_error(f"SMS send failed: {e}")
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
"""SMS is connected when Twilio credentials are present (bool(TWILIO_ACCOUNT_SID))."""
|
||||
import hermes_cli.gateway as gateway_mod
|
||||
return bool((gateway_mod.get_env_value("TWILIO_ACCOUNT_SID") or "").strip())
|
||||
_is_connected = _env_is_connected("TWILIO_ACCOUNT_SID")
|
||||
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
|
||||
@@ -17,7 +17,6 @@ import asyncio
|
||||
import importlib.util
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from contextlib import contextmanager, suppress
|
||||
@@ -58,7 +57,9 @@ from gateway.platforms.base import (
|
||||
gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, cache_image_from_url, cache_media_bytes_async,
|
||||
)
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.platforms._shared import coerce_port, get_scoped_secret as _get_scoped_secret, send_error
|
||||
from gateway.platforms._shared import (
|
||||
coerce_port, get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -167,28 +168,20 @@ def is_connected(config) -> bool:
|
||||
|
||||
|
||||
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."""
|
||||
# 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 = _get_scoped_secret("TEAMS_TENANT_ID", "").strip()
|
||||
if not (client_id and client_secret and tenant_id):
|
||||
"""``env_enablement_fn``: seed ``PlatformConfig.extra`` from the profile's env before adapter construction
|
||||
so ``gateway status`` reflects env-only setups without the SDK; ``None`` when not minimally configured.
|
||||
Every identity/endpoint is per-profile (the app the secret belongs to, its regional service URL, the
|
||||
cron home conversation), so a secondary is never seeded with the default profile's Teams app."""
|
||||
seed = _seed_extra_from_env((
|
||||
("TEAMS_CLIENT_ID", "client_id", None), ("TEAMS_CLIENT_SECRET", "client_secret", None),
|
||||
("TEAMS_TENANT_ID", "tenant_id", None), ("TEAMS_PORT", "port", int), ("TEAMS_SERVICE_URL", "service_url", None),
|
||||
), home_env="TEAMS_HOME_CHANNEL")
|
||||
if not all(seed.get(k) for k in ("client_id", "client_secret", "tenant_id")):
|
||||
return None
|
||||
seed: dict = {"client_id": client_id, "client_secret": client_secret, "tenant_id": tenant_id}
|
||||
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():
|
||||
seed["service_url"] = service_url
|
||||
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
|
||||
|
||||
|
||||
|
||||
async def _standalone_send(
|
||||
pconfig, chat_id: str, message: str, *,
|
||||
thread_id: Optional[str] = None, media_files: Optional[list] = None, force_document: bool = False,
|
||||
|
||||
@@ -18,6 +18,7 @@ from hermes_cli import setup_platforms
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from agent.deadline import run_bounded_async
|
||||
from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, platform_gate_env as _scoped_gate_env
|
||||
|
||||
|
||||
def _redact_telegram_error_text(error: object) -> str:
|
||||
@@ -32,21 +33,6 @@ def _redact_telegram_error_text(error: object) -> str:
|
||||
return "<telegram error redacted>"
|
||||
|
||||
|
||||
def _scoped_gate_env(name: str, default: str = "") -> str:
|
||||
"""Per-profile TELEGRAM_*/GATEWAY_* gate env read (multiplex env is first-writer-wins).
|
||||
|
||||
Under gateway.multiplex_profiles the process env is first-writer-wins (the YAML→env bridge in
|
||||
``_apply_yaml_config``), so a raw ``os.getenv`` can return ANOTHER profile's allowlist (issue #72348,
|
||||
Telegram mirror). Reads the active profile's secret scope when installed; falls back to ``os.getenv``
|
||||
outside multiplex — identical single-profile behavior.
|
||||
"""
|
||||
try:
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
return _platform_gate_env(name, default)
|
||||
except Exception:
|
||||
return (os.getenv(name) or default).strip()
|
||||
|
||||
|
||||
def _consume_abandoned_task(task: asyncio.Task) -> None:
|
||||
"""Observe a detached task's terminal exception to avoid noisy loop logs."""
|
||||
try:
|
||||
@@ -2851,12 +2837,7 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
webhook_port = env_int("TELEGRAM_WEBHOOK_PORT", 8443)
|
||||
# Default "" → tornado listens on IPv4 + IPv6; "0.0.0.0" is unreachable on IPv6-only networks.
|
||||
webhook_host = (os.getenv("TELEGRAM_WEBHOOK_HOST", "").strip() or str((self.config.extra or {}).get("webhook_host") or "").strip())
|
||||
# Profile-scoped read; only an UNSCOPED read under multiplex falls back to process env.
|
||||
from agent.secret_scope import UnscopedSecretError, get_secret
|
||||
try:
|
||||
webhook_secret = (get_secret("TELEGRAM_WEBHOOK_SECRET") or "").strip()
|
||||
except UnscopedSecretError:
|
||||
webhook_secret = os.getenv("TELEGRAM_WEBHOOK_SECRET", "").strip()
|
||||
webhook_secret = (_get_scoped_secret("TELEGRAM_WEBHOOK_SECRET") or "").strip()
|
||||
if not webhook_secret:
|
||||
raise RuntimeError(
|
||||
"TELEGRAM_WEBHOOK_SECRET is required when TELEGRAM_WEBHOOK_URL is set. Without it, the "
|
||||
@@ -2949,11 +2930,7 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
# 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()
|
||||
webhook_url = (_get_scoped_secret("TELEGRAM_WEBHOOK_URL") or "").strip()
|
||||
if webhook_url:
|
||||
await self._start_webhook_mode(webhook_url, is_reconnect=is_reconnect)
|
||||
else:
|
||||
|
||||
@@ -821,9 +821,6 @@ def _callback_is_connected(config) -> bool:
|
||||
return bool(extra.get("corp_id") or extra.get("apps"))
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
return WeComAdapter(config)
|
||||
|
||||
|
||||
def _build_callback_adapter(config):
|
||||
from plugins.platforms.wecom.callback_adapter import WecomCallbackAdapter
|
||||
@@ -833,7 +830,7 @@ def _build_callback_adapter(config):
|
||||
def register(ctx) -> None:
|
||||
common = dict(install_hint="Run `hermes setup` to install WeCom support.", emoji="💼", allow_update_command=True)
|
||||
ctx.register_platform(
|
||||
name="wecom", label="WeCom (Enterprise WeChat)", adapter_factory=_build_adapter, check_fn=check_wecom_requirements,
|
||||
name="wecom", label="WeCom (Enterprise WeChat)", adapter_factory=WeComAdapter, check_fn=check_wecom_requirements,
|
||||
is_connected=_is_connected, validate_config=_is_connected, required_env=["WECOM_BOT_ID", "WECOM_SECRET"],
|
||||
setup_fn=interactive_setup, allowed_users_env="WECOM_ALLOWED_USERS", allow_all_env="WECOM_ALLOW_ALL_USERS",
|
||||
cron_deliver_env_var="WECOM_HOME_CHANNEL", standalone_sender_fn=_standalone_send, max_message_length=4000, **common,
|
||||
|
||||
@@ -14,7 +14,9 @@ from functools import wraps
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional, Any
|
||||
|
||||
from gateway.platforms._shared import get_scoped_secret, send_error, yaml_env_setter
|
||||
from gateway.platforms._shared import (
|
||||
apply_yaml_bridge as _apply_yaml_bridge, get_scoped_secret, send_error
|
||||
)
|
||||
from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
|
||||
from hermes_constants import (find_node_executable, get_hermes_dir, with_hermes_node_path)
|
||||
|
||||
@@ -942,34 +944,19 @@ def interactive_setup() -> None:
|
||||
|
||||
|
||||
# config.yaml whatsapp: key → env var. Env vars take precedence over YAML.
|
||||
_YAML_LOWERCASE_KEYS = (("require_mention", "WHATSAPP_REQUIRE_MENTION"), ("dm_policy", "WHATSAPP_DM_POLICY"), ("group_policy", "WHATSAPP_GROUP_POLICY"))
|
||||
_YAML_LIST_KEYS = (("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS"), ("allow_from", "WHATSAPP_ALLOWED_USERS"), ("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS"))
|
||||
_YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
|
||||
("require_mention", "WHATSAPP_REQUIRE_MENTION", "lower"), ("dm_policy", "WHATSAPP_DM_POLICY", "lower"),
|
||||
("group_policy", "WHATSAPP_GROUP_POLICY", "lower"), ("mention_patterns", "WHATSAPP_MENTION_PATTERNS", "json"),
|
||||
("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS", "csv"), ("allow_from", "WHATSAPP_ALLOWED_USERS", "csv"),
|
||||
("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS", "csv"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, whatsapp_cfg: dict) -> dict | None:
|
||||
"""config.yaml whatsapp: keys → WHATSAPP_* env vars + ``PlatformConfig.extra`` (apply_yaml_config_fn).
|
||||
"""``apply_yaml_config_fn`` (#24849): config.yaml whatsapp: keys → WHATSAPP_* env (env wins; skipped under
|
||||
a multiplexed secondary profile's scope, #80099) + ``PlatformConfig.extra`` (extra-first readers)."""
|
||||
return _apply_yaml_bridge(whatsapp_cfg, _YAML_BRIDGE)
|
||||
|
||||
Mirrors the legacy whatsapp_cfg block from gateway/config.py::load_gateway_config(). Env vars take
|
||||
precedence over YAML. The env write is skipped under a multiplexed secondary profile's scope (#80099);
|
||||
every field has an extra-first reader (``WhatsAppAdapter.__init__`` policies/allowlists,
|
||||
``whatsapp_common`` require_mention/free_response_chats/mention_patterns). See #24849.
|
||||
"""
|
||||
import json as _json
|
||||
_set_env = yaml_env_setter()
|
||||
seeded: dict = {}
|
||||
for key, env in _YAML_LOWERCASE_KEYS:
|
||||
if key in whatsapp_cfg:
|
||||
seeded[key] = whatsapp_cfg[key]
|
||||
_set_env(env, str(whatsapp_cfg[key]).lower())
|
||||
if "mention_patterns" in whatsapp_cfg:
|
||||
seeded["mention_patterns"] = whatsapp_cfg["mention_patterns"]
|
||||
_set_env("WHATSAPP_MENTION_PATTERNS", _json.dumps(whatsapp_cfg["mention_patterns"]))
|
||||
for key, env in _YAML_LIST_KEYS:
|
||||
val = whatsapp_cfg.get(key)
|
||||
if val is not None:
|
||||
seeded[key] = val
|
||||
_set_env(env, val)
|
||||
return seeded or None
|
||||
|
||||
|
||||
def _is_connected(config) -> bool:
|
||||
@@ -981,13 +968,10 @@ def _is_connected(config) -> bool:
|
||||
return (gateway_mod.get_env_value("WHATSAPP_ENABLED") or "").strip().lower() in {"true", "1", "yes"}
|
||||
|
||||
|
||||
def _build_adapter(config):
|
||||
return WhatsAppAdapter(config)
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
ctx.register_platform(
|
||||
name="whatsapp", label="WhatsApp", adapter_factory=_build_adapter, check_fn=check_whatsapp_requirements,
|
||||
name="whatsapp", label="WhatsApp", adapter_factory=WhatsAppAdapter, check_fn=check_whatsapp_requirements,
|
||||
is_connected=_is_connected, required_env=["WHATSAPP_ENABLED"],
|
||||
install_hint="WhatsApp requires a Node.js bridge — see the WhatsApp messaging docs",
|
||||
setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="WHATSAPP_ALLOWED_USERS",
|
||||
|
||||
@@ -72,7 +72,7 @@ class TestPairingAllowlistRead:
|
||||
|
||||
class TestAuthzPlatformGateEnv:
|
||||
def test_scoped_value_wins(self, monkeypatch):
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
from gateway.platforms._shared import platform_gate_env as _platform_gate_env
|
||||
|
||||
monkeypatch.setenv("DISCORD_ALLOW_BOTS", "none")
|
||||
ss.set_multiplex_active(True)
|
||||
@@ -80,7 +80,7 @@ class TestAuthzPlatformGateEnv:
|
||||
assert _platform_gate_env("DISCORD_ALLOW_BOTS", "none") == "all"
|
||||
|
||||
def test_scoped_miss_returns_default_not_env(self, monkeypatch):
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
from gateway.platforms._shared import platform_gate_env as _platform_gate_env
|
||||
|
||||
monkeypatch.setenv("DISCORD_ALLOW_BOTS", "all") # another profile's bridge
|
||||
ss.set_multiplex_active(True)
|
||||
@@ -88,14 +88,14 @@ class TestAuthzPlatformGateEnv:
|
||||
assert _platform_gate_env("DISCORD_ALLOW_BOTS", "none") == "none"
|
||||
|
||||
def test_single_profile_legacy_env(self, monkeypatch):
|
||||
from gateway.authz_mixin import _platform_gate_env
|
||||
from gateway.platforms._shared import platform_gate_env as _platform_gate_env
|
||||
|
||||
monkeypatch.setenv("GATEWAY_ALLOWED_USERS", "42")
|
||||
assert _platform_gate_env("GATEWAY_ALLOWED_USERS") == "42"
|
||||
|
||||
|
||||
class TestAuthzAuthEnv:
|
||||
"""_auth_env must follow _platform_gate_env isolation (no os.environ
|
||||
"""_auth_env must follow platform_gate_env isolation (no os.environ
|
||||
fallthrough on a scoped miss under multiplex)."""
|
||||
|
||||
def test_scoped_value_wins(self, monkeypatch):
|
||||
@@ -129,8 +129,10 @@ class TestAuthzAuthEnv:
|
||||
|
||||
class TestMatrixStartupSecret:
|
||||
def _helper(self):
|
||||
mod = pytest.importorskip("plugins.platforms.matrix.adapter")
|
||||
return mod._startup_env_secret
|
||||
pytest.importorskip("plugins.platforms.matrix.adapter")
|
||||
from gateway.platforms._shared import get_scoped_secret
|
||||
|
||||
return lambda name: (get_scoped_secret(name, "") or "").strip()
|
||||
|
||||
def test_scoped_value_wins(self, monkeypatch):
|
||||
helper = self._helper()
|
||||
|
||||
@@ -71,7 +71,7 @@ _SETTINGS = [
|
||||
("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")),
|
||||
lambda m: m._extra_or_secret({}, "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",
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Invariants for the shared adapter boilerplate in ``gateway/platforms/_shared.py``.
|
||||
|
||||
Contract under test: every plugin platform's env-driven enablement reads through the ONE
|
||||
profile-scoped reader (never an ambient ``os.environ``/``get_env_value`` read), and the table-driven
|
||||
``apply_yaml_bridge`` seeds ``extra`` for a secondary profile even though it must not write env.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import agent.secret_scope as ss
|
||||
import gateway.platforms._shared as shared
|
||||
import hermes_cli.config as cli_config
|
||||
|
||||
_ENV_ENABLEMENT_PLUGINS = ("buzz", "google_chat", "irc", "line", "ntfy", "photon", "simplex", "teams")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _multiplex_off():
|
||||
prev = ss._MULTIPLEX_ACTIVE
|
||||
ss.set_multiplex_active(False)
|
||||
yield
|
||||
ss.set_multiplex_active(prev)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plugin", _ENV_ENABLEMENT_PLUGINS)
|
||||
def test_env_enablement_reads_only_through_scoped_getter(plugin, monkeypatch):
|
||||
"""A secondary profile is seeded only from its own scope: every var the hook consults must go through
|
||||
``_shared.get_scoped_secret`` (a fake scope answers them) and never through a raw env read."""
|
||||
mod = importlib.import_module(f"plugins.platforms.{plugin}.adapter")
|
||||
# Anything the plugin resolves through raw env would be visible here; the scoped reader hides it.
|
||||
for var in list(os.environ):
|
||||
if var.startswith(plugin.upper().replace("GOOGLE_CHAT", "GOOGLE")):
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
fake_scope = {
|
||||
"BUZZ_RELAY_URL": "wss://relay", "BUZZ_PRIVATE_KEY": "k" * 8, "BUZZ_CHANNELS": "a,b",
|
||||
"GOOGLE_CHAT_PROJECT_ID": "p", "GOOGLE_CHAT_SUBSCRIPTION_NAME": "s", "GOOGLE_CHAT_MAX_MESSAGES": "3",
|
||||
"IRC_SERVER": "irc.example", "IRC_CHANNEL": "#h", "IRC_PORT": "6697",
|
||||
"LINE_CHANNEL_ACCESS_TOKEN": "t", "LINE_CHANNEL_SECRET": "s", "LINE_PORT": "8081",
|
||||
"NTFY_TOPIC": "topic", "NTFY_TOKEN": "tok",
|
||||
"PHOTON_PROJECT_ID": "pid", "PHOTON_PROJECT_SECRET": "sec", "PHOTON_HOME_CHANNEL": "line-1",
|
||||
"SIMPLEX_WS_URL": "ws://x", "SIMPLEX_GROUP_ALLOWED": "g",
|
||||
"TEAMS_CLIENT_ID": "c", "TEAMS_CLIENT_SECRET": "s", "TEAMS_TENANT_ID": "t", "TEAMS_PORT": "3979",
|
||||
}
|
||||
scoped_hits: list[str] = []
|
||||
raw_hits: list[str] = []
|
||||
real = shared.get_scoped_secret
|
||||
|
||||
def spy(name, default=None, **kw):
|
||||
scoped_hits.append(name)
|
||||
return fake_scope.get(name, default)
|
||||
|
||||
monkeypatch.setattr(shared, "get_scoped_secret", spy)
|
||||
monkeypatch.setattr(shared, "_scoped_get_secret", lambda name, default=None: fake_scope.get(name, default))
|
||||
monkeypatch.setattr(cli_config, "get_env_value", lambda key: raw_hits.append(key))
|
||||
monkeypatch.setattr(os, "getenv", lambda key, default=None: raw_hits.append(key) or default)
|
||||
|
||||
seed = mod._env_enablement()
|
||||
|
||||
assert real is not shared.get_scoped_secret # the spy really replaced the seam
|
||||
assert seed, f"{plugin}: fake scope holds the required vars, hook must enable"
|
||||
assert scoped_hits, f"{plugin}: enablement never touched the scoped reader"
|
||||
assert not raw_hits, f"{plugin}: raw env reads during enablement: {raw_hits}"
|
||||
|
||||
|
||||
def test_home_channel_name_defaults_to_home_everywhere(monkeypatch):
|
||||
"""One rule for ``home_channel.name`` across adapters: ``<HOME_ENV>_NAME`` else the literal ``Home``
|
||||
(irc/ntfy/buzz previously used the chat id as its own name)."""
|
||||
monkeypatch.setattr(shared, "get_scoped_secret", lambda n, d=None, **k: {"X_HOME": "room"}.get(n, d))
|
||||
seed = shared.seed_extra_from_env((), home_env="X_HOME")
|
||||
assert seed["home_channel"] == {"chat_id": "room", "name": "Home"}
|
||||
monkeypatch.setattr(shared, "get_scoped_secret", lambda n, d=None, **k: {"X_HOME": "room", "X_HOME_NAME": "Ops"}.get(n, d))
|
||||
assert shared.seed_extra_from_env((), home_env="X_HOME")["home_channel"]["name"] == "Ops"
|
||||
assert shared.seed_extra_from_env((), home_env="X_HOME", home_default="fallback")["home_channel"]["chat_id"] == "room"
|
||||
monkeypatch.setattr(shared, "get_scoped_secret", lambda n, d=None, **k: d)
|
||||
assert shared.seed_extra_from_env((), home_env="X_HOME", home_default="fallback")["home_channel"]["chat_id"] == "fallback"
|
||||
assert "home_channel" not in shared.seed_extra_from_env((), home_env="X_HOME")
|
||||
|
||||
|
||||
def test_buzz_yaml_bridge_seeds_extra_for_a_secondary_profile(monkeypatch):
|
||||
"""Under a secondary profile's scope the env write is skipped, so the hook MUST return the values for
|
||||
``PlatformConfig.extra`` — a ``None`` return left a secondary Buzz profile with neither."""
|
||||
import plugins.platforms.buzz.adapter as buzz
|
||||
|
||||
for var in ("BUZZ_RELAY_URL", "BUZZ_REPLY_TO_MODE", "BUZZ_CHANNELS", "BUZZ_REQUIRE_MENTION"):
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
monkeypatch.setattr(shared, "profile_scoped", lambda: True)
|
||||
seeded = buzz._apply_yaml_config({}, {"extra": {
|
||||
"relay_url": "wss://p.relay", "reply_to_mode": "off", "channels": ["a", "b"], "require_mention": False}})
|
||||
assert seeded == {"relay_url": "wss://p.relay", "reply_to_mode": "off", "channels": ["a", "b"], "require_mention": False}
|
||||
assert not any(v in os.environ for v in ("BUZZ_RELAY_URL", "BUZZ_REPLY_TO_MODE", "BUZZ_CHANNELS", "BUZZ_REQUIRE_MENTION"))
|
||||
|
||||
monkeypatch.setattr(shared, "profile_scoped", lambda: False)
|
||||
buzz._apply_yaml_config({}, {"extra": {"reply_to_mode": "off", "channels": ["a", "b"], "require_mention": False}})
|
||||
assert os.environ["BUZZ_REPLY_TO_MODE"] == "off"
|
||||
assert os.environ["BUZZ_CHANNELS"] == "a,b"
|
||||
assert os.environ["BUZZ_REQUIRE_MENTION"] == "false"
|
||||
for var in ("BUZZ_REPLY_TO_MODE", "BUZZ_CHANNELS", "BUZZ_REQUIRE_MENTION"):
|
||||
monkeypatch.delenv(var, raising=False)
|
||||
|
||||
|
||||
def test_extra_or_secret_honours_explicit_false_but_not_blank(monkeypatch):
|
||||
monkeypatch.setattr(shared, "get_scoped_secret", lambda n, d=None, **k: f"env:{d}")
|
||||
assert shared.extra_or_secret({"require_mention": False}, "require_mention", "X", "true") is False
|
||||
assert shared.extra_or_secret({"require_mention": ""}, "require_mention", "X", "true") == "env:true"
|
||||
assert shared.extra_or_secret(None, "require_mention", "X", "true") == "env:true"
|
||||
|
||||
|
||||
def test_external_fallback_consults_profile_scope_only_when_unscoped(monkeypatch):
|
||||
"""Buzz's startup gate rung: a Bitwarden-managed key is visible through ``external_fallback`` before any
|
||||
scope exists, but never overrides an installed (authoritative) scope."""
|
||||
monkeypatch.delenv("K", raising=False)
|
||||
monkeypatch.setattr(shared, "_UNSCOPED_PROFILE_SECRETS", {"K": "external"})
|
||||
assert shared.get_scoped_secret("K") is None
|
||||
assert shared.get_scoped_secret("K", external_fallback=True) == "external"
|
||||
ss.set_multiplex_active(True)
|
||||
token = ss.set_secret_scope({"OTHER": "x"})
|
||||
try:
|
||||
assert shared.get_scoped_secret("K", "dflt", external_fallback=True) == "dflt"
|
||||
finally:
|
||||
ss.reset_secret_scope(token)
|
||||
@@ -4,7 +4,7 @@
|
||||
secret scope is installed, so a Bitwarden-managed ``BUZZ_PRIVATE_KEY`` (only
|
||||
``BWS_ACCESS_TOKEN`` in ``.env``) was invisible to the bare env read and Buzz
|
||||
was silently skipped. The fix adds a one-shot ``build_profile_secret_scope``
|
||||
consultation to the unscoped fallback of ``_get_scoped_secret``.
|
||||
consultation to the unscoped fallback of ``_shared.get_scoped_secret(external_fallback=True)``.
|
||||
|
||||
The key values below are synthesized placeholders (never a usable secret).
|
||||
"""
|
||||
@@ -20,12 +20,12 @@ _STUB_KEY = os.environ.get("BUZZ_TEST_STUB_KEY") or ("k" * 8)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_unscoped_cache():
|
||||
import plugins.platforms.buzz.adapter as adapter
|
||||
import gateway.platforms._shared as shared
|
||||
|
||||
prev = adapter._UNSCOPED_PROFILE_SECRETS
|
||||
adapter._UNSCOPED_PROFILE_SECRETS = None
|
||||
prev = shared._UNSCOPED_PROFILE_SECRETS
|
||||
shared._UNSCOPED_PROFILE_SECRETS = None
|
||||
yield
|
||||
adapter._UNSCOPED_PROFILE_SECRETS = prev
|
||||
shared._UNSCOPED_PROFILE_SECRETS = prev
|
||||
|
||||
|
||||
def _install_fake_scope(monkeypatch, secrets):
|
||||
|
||||
@@ -92,7 +92,7 @@ be granted its own outbound tools.
|
||||
### adapter.py
|
||||
|
||||
```python
|
||||
import os
|
||||
from gateway.platforms._shared import extra_or_secret, get_scoped_secret, seed_extra_from_env
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
@@ -101,8 +101,8 @@ from gateway.config import Platform, PlatformConfig
|
||||
class MyPlatformAdapter(BasePlatformAdapter):
|
||||
def __init__(self, config: PlatformConfig):
|
||||
super().__init__(config, Platform("my_platform"))
|
||||
extra = config.extra or {}
|
||||
self.token = os.getenv("MY_PLATFORM_TOKEN") or extra.get("token", "")
|
||||
# config.extra first (the per-profile truth under multiplexing), then the profile-scoped env var.
|
||||
self.token = extra_or_secret(config.extra, "token", "MY_PLATFORM_TOKEN")
|
||||
|
||||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||||
# Connect to the platform API, start listeners
|
||||
@@ -121,24 +121,20 @@ class MyPlatformAdapter(BasePlatformAdapter):
|
||||
|
||||
|
||||
def check_requirements() -> bool:
|
||||
return bool(os.getenv("MY_PLATFORM_TOKEN"))
|
||||
return bool(get_scoped_secret("MY_PLATFORM_TOKEN"))
|
||||
|
||||
|
||||
def validate_config(config) -> bool:
|
||||
extra = getattr(config, "extra", {}) or {}
|
||||
return bool(os.getenv("MY_PLATFORM_TOKEN") or extra.get("token"))
|
||||
return bool(extra_or_secret(getattr(config, "extra", None), "token", "MY_PLATFORM_TOKEN"))
|
||||
|
||||
|
||||
def _env_enablement() -> dict | None:
|
||||
token = os.getenv("MY_PLATFORM_TOKEN", "").strip()
|
||||
channel = os.getenv("MY_PLATFORM_CHANNEL", "").strip()
|
||||
if not (token and channel):
|
||||
if not get_scoped_secret("MY_PLATFORM_TOKEN", "").strip():
|
||||
return None
|
||||
seed = {"token": token, "channel": channel}
|
||||
home = os.getenv("MY_PLATFORM_HOME_CHANNEL")
|
||||
if home:
|
||||
seed["home_channel"] = {"chat_id": home, "name": "Home"}
|
||||
return seed
|
||||
return seed_extra_from_env(
|
||||
(("MY_PLATFORM_TOKEN", "token", None), ("MY_PLATFORM_CHANNEL", "channel", None)),
|
||||
home_env="MY_PLATFORM_HOME_CHANNEL",
|
||||
)
|
||||
|
||||
|
||||
def register(ctx):
|
||||
@@ -146,7 +142,7 @@ def register(ctx):
|
||||
ctx.register_platform(
|
||||
name="my_platform",
|
||||
label="My Platform",
|
||||
adapter_factory=lambda cfg: MyPlatformAdapter(cfg),
|
||||
adapter_factory=MyPlatformAdapter,
|
||||
# PASSIVE probe — "are deps/config present right now?". Called from
|
||||
# status displays and config loading, so it must NEVER pip-install.
|
||||
check_fn=check_requirements,
|
||||
@@ -295,37 +291,38 @@ the next profile.
|
||||
|
||||
Most users set up a platform by dropping env vars into `~/.hermes/.env` rather than editing `config.yaml`. The `env_enablement_fn` hook lets your plugin pick those env vars up **before** the adapter is constructed, so `hermes gateway status`, `get_connected_platforms()`, and cron delivery see the correct state without instantiating the platform SDK.
|
||||
|
||||
Read env through `gateway.platforms._shared.get_scoped_secret` — never `os.getenv`. Under `gateway.multiplex_profiles` the process env holds the DEFAULT profile's values; a secondary profile's `.env` exists only in its secret scope, and a raw read would enable your platform for the wrong profile with the wrong credentials. `seed_extra_from_env` builds the seed dict from a `(ENV_VAR, extra_key, conv)` table through that reader.
|
||||
|
||||
```python
|
||||
from gateway.platforms._shared import get_scoped_secret, seed_extra_from_env
|
||||
|
||||
|
||||
def _env_enablement() -> dict | None:
|
||||
"""Seed PlatformConfig.extra from env vars.
|
||||
|
||||
Called by the platform registry during load_gateway_config().
|
||||
Return None when the platform isn't minimally configured — the
|
||||
caller then skips auto-enabling. Return a dict to seed extras.
|
||||
|
||||
The special 'home_channel' key is extracted and becomes a proper
|
||||
HomeChannel dataclass on the PlatformConfig; every other key is
|
||||
merged into PlatformConfig.extra.
|
||||
"""
|
||||
token = os.getenv("MY_PLATFORM_TOKEN", "").strip()
|
||||
channel = os.getenv("MY_PLATFORM_CHANNEL", "").strip()
|
||||
token = get_scoped_secret("MY_PLATFORM_TOKEN", "").strip()
|
||||
channel = get_scoped_secret("MY_PLATFORM_CHANNEL", "").strip()
|
||||
if not (token and channel):
|
||||
return None
|
||||
seed = {"token": token, "channel": channel}
|
||||
home = os.getenv("MY_PLATFORM_HOME_CHANNEL")
|
||||
if home:
|
||||
seed["home_channel"] = {
|
||||
"chat_id": home,
|
||||
"name": os.getenv("MY_PLATFORM_HOME_CHANNEL_NAME", "Home"),
|
||||
}
|
||||
return seed
|
||||
# (ENV_VAR, extra_key, conv): blank values are skipped, a conv raising
|
||||
# ValueError drops the key. home_env seeds the special 'home_channel'
|
||||
# dict ({chat_id, name} from MY_PLATFORM_HOME_CHANNEL[_NAME], name
|
||||
# defaults to "Home"), which the core hook lifts into a HomeChannel.
|
||||
return {"token": token, "channel": channel, **seed_extra_from_env(
|
||||
(("MY_PLATFORM_PORT", "port", int), ("MY_PLATFORM_NICK", "nick", None)),
|
||||
home_env="MY_PLATFORM_HOME_CHANNEL",
|
||||
)}
|
||||
|
||||
|
||||
def register(ctx):
|
||||
ctx.register_platform(
|
||||
name="my_platform",
|
||||
label="My Platform",
|
||||
adapter_factory=lambda cfg: MyPlatformAdapter(cfg),
|
||||
adapter_factory=MyPlatformAdapter,
|
||||
check_fn=check_requirements,
|
||||
validate_config=validate_config,
|
||||
env_enablement_fn=_env_enablement,
|
||||
@@ -339,7 +336,16 @@ def register(ctx):
|
||||
Some users prefer setting `config.yaml` keys (`my_platform.require_mention`, `my_platform.allowed_channels`, etc.) over env vars. The `apply_yaml_config_fn` hook lets your plugin own this translation instead of forcing core `gateway/config.py` to know your platform's YAML schema.
|
||||
|
||||
```python
|
||||
import os
|
||||
from gateway.platforms._shared import apply_yaml_bridge
|
||||
|
||||
# (yaml key, ENV_VAR, kind). "lower" bridges whenever the key is present
|
||||
# (booleans become "true"/"false"); "str" skips null/blank; "csv" comma-joins
|
||||
# lists; "json" dumps the value.
|
||||
_YAML_BRIDGE = (
|
||||
("require_mention", "MY_PLATFORM_REQUIRE_MENTION", "lower"),
|
||||
("allowed_channels", "MY_PLATFORM_ALLOWED_CHANNELS", "csv"),
|
||||
)
|
||||
|
||||
|
||||
def _apply_yaml_config(yaml_cfg: dict, platform_cfg: dict) -> dict | None:
|
||||
"""Translate config.yaml `my_platform:` keys into env vars / extras.
|
||||
@@ -347,18 +353,13 @@ def _apply_yaml_config(yaml_cfg: dict, platform_cfg: dict) -> dict | None:
|
||||
yaml_cfg — the full top-level parsed config.yaml dict
|
||||
platform_cfg — the platform's own sub-dict (yaml_cfg.get("my_platform", {}))
|
||||
|
||||
May mutate os.environ directly (use `not os.getenv(...)` guards to
|
||||
preserve env > YAML precedence) and/or return a dict to merge into
|
||||
PlatformConfig.extra. Return None or {} for no extras.
|
||||
apply_yaml_bridge writes each env var only when it is unset (env > YAML)
|
||||
and NEVER while a multiplexed secondary profile's config is loading — a
|
||||
write there would pin that profile's policy process-wide. It returns the
|
||||
same values for PlatformConfig.extra, so read `extra` first in the adapter
|
||||
and fall back to the env var (`_shared.extra_or_secret`).
|
||||
"""
|
||||
if "require_mention" in platform_cfg and not os.getenv("MY_PLATFORM_REQUIRE_MENTION"):
|
||||
os.environ["MY_PLATFORM_REQUIRE_MENTION"] = str(platform_cfg["require_mention"]).lower()
|
||||
allowed = platform_cfg.get("allowed_channels")
|
||||
if allowed is not None and not os.getenv("MY_PLATFORM_ALLOWED_CHANNELS"):
|
||||
if isinstance(allowed, list):
|
||||
allowed = ",".join(str(v) for v in allowed)
|
||||
os.environ["MY_PLATFORM_ALLOWED_CHANNELS"] = str(allowed)
|
||||
return None # nothing extra to merge into PlatformConfig.extra
|
||||
return apply_yaml_bridge(platform_cfg, _YAML_BRIDGE)
|
||||
|
||||
def register(ctx):
|
||||
ctx.register_platform(
|
||||
@@ -573,6 +574,7 @@ Create `plugins/platforms/newplat/adapter.py`:
|
||||
|
||||
```python
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
from gateway.platforms._shared import extra_or_secret
|
||||
from gateway.platforms.base import BasePlatformAdapter, SendResult
|
||||
from gateway.platforms.event import MessageEvent, MessageType
|
||||
|
||||
@@ -585,7 +587,7 @@ class NewPlatAdapter(BasePlatformAdapter):
|
||||
super().__init__(config, Platform.NEWPLAT)
|
||||
# Read config from config.extra dict
|
||||
extra = config.extra or {}
|
||||
self._api_key = extra.get("api_key") or os.getenv("NEWPLAT_API_KEY", "")
|
||||
self._api_key = extra_or_secret(extra, "api_key", "NEWPLAT_API_KEY")
|
||||
|
||||
async def connect(self, *, is_reconnect: bool = False) -> bool:
|
||||
# Set up connection, start polling/webhook
|
||||
|
||||
Reference in New Issue
Block a user