Skip to content

The agent that grows with you

refactor(gateway): bot-bypass and own-policy startup gates read the PlatformEntry

Teknium2ab1a408d026
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index 501d72de6ec..6de9adb3e3f 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -41,16 +41,6 @@ _ALLOWLIST_SUPPRESSES_PAIRING = frozenset({
})
_GROUP_USER_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_USERS"}
_GROUP_CHAT_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS"}
-_ALLOW_BOTS_ENV = {
- # Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist (#4466). Checked before the
- # no-user-id guard below: some platforms deliver bot/automation traffic with no user_id at all -- e.g.
- # Slack Workflow Builder posts arrive as subtype=bot_message with user=None -- so deferring past the
- # guard would reject them outright (the same reason the chat-scoped allowlist above runs early).
- Platform.DISCORD: "DISCORD_ALLOW_BOTS",
- Platform.FEISHU: "FEISHU_ALLOW_BOTS",
- Platform.TELEGRAM: "TELEGRAM_ALLOW_BOTS",
- Platform.SLACK: "SLACK_ALLOW_BOTS",
-}
# Gate reads use the shared per-profile isolated reader (allowlist leak under multiplex, #72348).
@@ -566,11 +556,18 @@ class GatewayAuthorizationMixin:
adapter_group_allowed = self._adapter_extra_for_source(source).get("group_allowed_chats")
if adapter_group_allowed and _allows(_coerce_allow_set(adapter_group_allowed), source.chat_id):
return True
- # Bots admitted by {PLATFORM}_ALLOW_BOTS (scoped env → the routed adapter's YAML ``allow_bots`` →
- # none) bypass the human allowlist (Slack Workflow Builder posts arrive with user=None). The YAML
- # rung is what a secondary profile has: its config is never bridged into the process env.
+ # Bots admitted by the platform's ``allow_bots_env`` (scoped env → the routed adapter's YAML
+ # ``allow_bots`` → none) bypass the human allowlist (#4466). Checked here, before the no-user-id
+ # guard: Slack Workflow Builder posts arrive as subtype=bot_message with user=None. The YAML rung
+ # is what a secondary profile has: its config is never bridged into the process env. No entry
+ # (plugin not loaded) = no bypass: fails closed.
if getattr(source, "is_bot", False):
- allow_bots_var = _ALLOW_BOTS_ENV.get(source.platform)
+ # Idempotent: the env name lives on the plugin's entry, so a runner that never ran the
+ # config passes (which discover) must still see it rather than silently deny.
+ with contextlib.suppress(Exception):
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ allow_bots_var = getattr(_registry_entry(source.platform), "allow_bots_env", "")
if allow_bots_var:
extra = {}
with contextlib.suppress(Exception):
diff --git a/gateway/platform_registry.py b/gateway/platform_registry.py
index 4aa97be9588..d4f08d51921 100644
--- a/gateway/platform_registry.py
+++ b/gateway/platform_registry.py
@@ -126,6 +126,14 @@ class PlatformEntry:
# than a token (Weixin: token AND account_id) can refuse it. None = ``token or api_key``, then
# ``is_connected`` / ``validate_config``.
config_connected_fn: Optional[Callable[[Any], bool]] = None
+ # --- authz ---
+ # ``<PLATFORM>_ALLOW_BOTS`` (YAML ``allow_bots`` wins): bot senders it admits ("mentions"/"all")
+ # bypass the human allowlist, checked before the no-user-id guard. "" = bots get no bypass.
+ allow_bots_env: str = ""
+ # (dm_policy_env, group_policy_env) of a platform with its own dm/group policy: when enabled and
+ # either resolves "open" without ``allow_all_env`` / GATEWAY_ALLOW_ALL_USERS, startup is refused.
+ # A "" member = that policy is YAML-only (QQ Bot). None = no own policy, never checked.
+ own_policy_env: Optional[tuple] = None
def core_ships_platform(name: str) -> bool:
diff --git a/gateway/run.py b/gateway/run.py
index 955cda5080b..96e9c7fc39e 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2197,7 +2197,7 @@ from gateway.run_turn import GatewayTurnMixin, is_context_overflow_failure_resul
from gateway.run_shutdown import GatewayShutdownMixin, _resolve_gateway_exit_verdict
from gateway.run_busy import GatewayBusySessionMixin
from gateway.run_config_loaders import GatewayConfigLoadersMixin
-from gateway.run_startup import GatewayStartupMixin
+from gateway.run_startup import GatewayStartupMixin, _own_policy_envs
from gateway.run_watchers import GatewaySessionWatchersMixin
from gateway.run_notifications import GatewayNotificationsMixin
from gateway.run_inbound import GatewayInboundMixin
@@ -2236,20 +2236,15 @@ def _best_effort(fn: Callable[[], Any], debug_msg: Optional[str] = None) -> Any:
_EXECUTOR_QUIESCE_TIMEOUT = 2.0
-_OWN_POLICY_OPEN_ENV = {
- Platform.WECOM: ("WECOM_DM_POLICY", "WECOM_GROUP_POLICY", "WECOM_ALLOW_ALL_USERS"),
- Platform.WEIXIN: ("WEIXIN_DM_POLICY", "WEIXIN_GROUP_POLICY", "WEIXIN_ALLOW_ALL_USERS"),
- Platform.YUANBAO: ("YUANBAO_DM_POLICY", "YUANBAO_GROUP_POLICY", "YUANBAO_ALLOW_ALL_USERS"),
- Platform.QQBOT: (None, None, "QQ_ALLOW_ALL_USERS"),
- Platform.WHATSAPP: ("WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY", "WHATSAPP_ALLOW_ALL_USERS")}
-
-
def _own_policy_open_startup_violation(config) -> Optional[str]:
"""Return a startup-abort reason when open policy lacks allow-all opt-in."""
+ with suppress(Exception): # idempotent; callers may hand in a config load_gateway_config never built
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
for platform, platform_config in getattr(config, "platforms", {}).items():
if not getattr(platform_config, "enabled", False):
continue
- open_env = _OWN_POLICY_OPEN_ENV.get(platform)
+ open_env = _own_policy_envs(platform)
if not open_env:
continue
dm_env, group_env, allow_all_env = open_env
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index e03b5f21a6b..d047cecd879 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -60,6 +60,31 @@ def recover_left_core_at_gateway_start() -> None:
recover_left_core_in(root)
+
+def _own_policy_envs(platform) -> Optional[tuple]:
+ """``(dm_policy_env, group_policy_env, allow_all_env)`` when the plugin's PlatformEntry declares
+ ``own_policy_env`` (an enabled platform's lookup imports only that adapter, which the gateway
+ builds anyway), else None. A bundled platform with NO entry (plugin disabled / failed to load)
+ fails CLOSED on the ``<NAME>_*`` names (allow-all: the one its manifest declares, e.g. QQ's
+ ``QQ_ALLOW_ALL_USERS``): its config can still enable it, and enabling the plugin later re-wires
+ the adapter into the live gateway without re-running the startup check."""
+ from gateway.platform_registry import platform_registry
+ entry = platform_registry.get(platform.value)
+ if entry is None and platform.value in Platform._scan_bundled_plugin_platforms()[0]:
+ prefix, declared = platform.value.upper(), []
+ with suppress(Exception):
+ from utils import fast_safe_load
+ manifest = Path(__file__).resolve().parent.parent / "plugins" / "platforms" / platform.value / "plugin.yaml"
+ data = fast_safe_load(manifest.read_text(encoding="utf-8-sig")) or {}
+ declared = [str(e.get("name", "")) for e in (*data.get("requires_env", ()), *data.get("optional_env", ()))
+ if isinstance(e, dict) and str(e.get("name", "")).endswith("_ALLOW_ALL_USERS")]
+ allow_all = declared[0] if len(declared) == 1 else f"{prefix}_ALLOW_ALL_USERS"
+ return f"{prefix}_DM_POLICY", f"{prefix}_GROUP_POLICY", allow_all
+ if entry is None or entry.own_policy_env is None:
+ return None
+ return (*entry.own_policy_env, entry.allow_all_env)
+
+
class GatewayStartupMixin:
"""Startup sequence, resume/restore and handoff methods for GatewayRunner."""
@@ -1014,7 +1039,7 @@ class GatewayStartupMixin:
def _start_check_access_policy(self) -> bool:
"""Warn about missing allowlists; return True when startup must be refused."""
from gateway.run import (
- _OWN_POLICY_OPEN_ENV, _own_policy_open_startup_violation, _write_runtime_status_quiet
+ _own_policy_open_startup_violation, _write_runtime_status_quiet
)
# Plugin platforms declare their own allowed_users_env / allow_all_env.
allowed_vars = list(self._BUILTIN_ALLOWED_USERS_VARS)
@@ -1046,9 +1071,7 @@ class GatewayStartupMixin:
reason = _own_policy_open_startup_violation(self.config)
if reason:
platform_value = reason.split(":", 1)[0]
- allow_all_env = next(
- (env[2] for p, env in _OWN_POLICY_OPEN_ENV.items() if p.value == platform_value), None
- )
+ allow_all_env = (_own_policy_envs(Platform(platform_value)) or (None, None, None))[2]
logger.error(
"Refusing to start: %s has dm_policy/group_policy set to 'open' "
"but neither GATEWAY_ALLOW_ALL_USERS nor %s is enabled.", platform_value,
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index 15213f57850..51fa8798d7b 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -7388,7 +7388,6 @@ def register(ctx) -> None:
required_env=["DISCORD_BOT_TOKEN"],
install_hint="Run `hermes setup` to install Discord support.",
setup_fn=interactive_setup,
- # YAML→env bridge: ``discord:`` config keys → ``DISCORD_*`` env vars read via os.getenv().
# YAML→env config bridge — owns the translation of ``config.yaml`` ``discord:`` keys
# (require_mention, free_response_channels, auto_thread, free_response_auto_thread,
# reactions, ignored_channels, allowed_channels, no_thread_channels, allow_mentions.*,
@@ -7398,6 +7397,7 @@ def register(ctx) -> None:
apply_yaml_config_fn=_apply_yaml_config,
allowed_users_env="DISCORD_ALLOWED_USERS",
allow_all_env="DISCORD_ALLOW_ALL_USERS",
+ allow_bots_env="DISCORD_ALLOW_BOTS",
cron_deliver_env_var="DISCORD_HOME_CHANNEL",
# Out-of-process cron delivery via REST, else ``deliver=discord`` jobs fail with "No live adapter".
standalone_sender_fn=_standalone_send,
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 950694c32df..c168581b824 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -4470,7 +4470,6 @@ def _apply_yaml_config(yaml_cfg: dict, feishu_cfg: dict) -> dict | None:
return {"allow_bots": str(seeded["allow_bots"]).lower()} if seeded else None
-
def _is_connected(config) -> bool:
"""Feishu counts as connected once app_id is configured."""
extra = getattr(config, "extra", {}) or {}
@@ -4490,4 +4489,5 @@ def register(ctx) -> None:
allow_all_env="FEISHU_ALLOW_ALL_USERS", cron_deliver_env_var="FEISHU_HOME_CHANNEL",
standalone_sender_fn=_standalone_send, max_message_length=8000, emoji="🪽",
allow_update_command=True,
+ allow_bots_env="FEISHU_ALLOW_BOTS",
)
diff --git a/plugins/platforms/qqbot/register.py b/plugins/platforms/qqbot/register.py
index 26f58d12ab2..900a603f1d6 100644
--- a/plugins/platforms/qqbot/register.py
+++ b/plugins/platforms/qqbot/register.py
@@ -138,4 +138,6 @@ def register(ctx) -> None:
emoji="🐧",
cron_deliver_env_var="QQBOT_HOME_CHANNEL",
standalone_sender_fn=standalone_send,
+ # QQ's dm/group policy is YAML-only (no env var); QQ_ALLOW_ALL_USERS is still the opt-in.
+ own_policy_env=("", ""),
)
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index 3ca74ef0ffa..2521cbea695 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -6921,7 +6921,6 @@ def register(ctx) -> None:
required_env=["SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"],
install_hint="Run `hermes setup` to install Slack support.",
setup_fn=interactive_setup,
- # YAML→env bridge: config.yaml slack: keys → SLACK_* env vars read via os.getenv().
# YAML→env config bridge — owns the translation of config.yaml slack: keys (require_mention,
# strict_mention, ignore_other_user_mentions, thread_require_mention, allow_bots,
# free_response_channels, reactions, disable_dms, allowed_channels, ignored_channels) into SLACK_*
@@ -6937,4 +6936,5 @@ def register(ctx) -> None:
# Slack allows 40,000 chars; leave margin.
max_message_length=39000,
emoji="💼",
- allow_update_command=True)
+ allow_update_command=True,
+ allow_bots_env="SLACK_ALLOW_BOTS")
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 54b6eb8f70d..fb0869a1a8b 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -7288,8 +7288,7 @@ def _apply_yaml_config(yaml_cfg: dict, telegram_cfg: dict) -> dict | None:
if _telegram_rtm is not None:
_set_env("TELEGRAM_REPLY_TO_MODE", "off" if _telegram_rtm is False else str(_telegram_rtm).lower())
_bridge_gate("allow_from", "TELEGRAM_ALLOWED_USERS", telegram_cfg.get("allow_from"))
- _bridge_gate(
- "group_allow_from", "TELEGRAM_GROUP_ALLOWED_USERS", telegram_cfg.get("group_allow_from") or _telegram_extra.get("group_allow_from"))
+ _bridge_gate("group_allow_from", "TELEGRAM_GROUP_ALLOWED_USERS", telegram_cfg.get("group_allow_from") or _telegram_extra.get("group_allow_from"))
_bridge_gate(
"group_allowed_chats", "TELEGRAM_GROUP_ALLOWED_CHATS",
telegram_cfg.get("group_allowed_chats") or _telegram_extra.get("group_allowed_chats"))
@@ -7315,4 +7314,5 @@ def register(ctx) -> None:
ensure_deps_fn=check_telegram_requirements, is_connected=_is_connected, required_env=["TELEGRAM_BOT_TOKEN"],
install_hint=t("platform.telegram.install_hint"), setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config,
allowed_users_env="TELEGRAM_ALLOWED_USERS", allow_all_env="TELEGRAM_ALLOW_ALL_USERS", cron_deliver_env_var="TELEGRAM_HOME_CHANNEL",
- standalone_sender_fn=_standalone_send, max_message_length=4096, emoji="✈️", allow_update_command=True)
+ standalone_sender_fn=_standalone_send, max_message_length=4096, emoji="✈️", allow_update_command=True,
+ allow_bots_env="TELEGRAM_ALLOW_BOTS")
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index 63290237503..8ca5384fe74 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -841,6 +841,7 @@ def register(ctx) -> None:
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,
+ own_policy_env=("WECOM_DM_POLICY", "WECOM_GROUP_POLICY"),
)
from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements, ensure_wecom_callback_requirements
ctx.register_platform(
diff --git a/plugins/platforms/weixin/adapter.py b/plugins/platforms/weixin/adapter.py
index aa1ce02019d..88ffa6f31d2 100644
--- a/plugins/platforms/weixin/adapter.py
+++ b/plugins/platforms/weixin/adapter.py
@@ -1400,4 +1400,6 @@ def register(ctx) -> None:
cron_deliver_env_var="WEIXIN_HOME_CHANNEL",
# Out-of-process send_message/cron; the adapter's own send() chunks (MAX_MESSAGE_LENGTH), so
# max_message_length stays 0: send_message hands the full text + all media to one native send.
- standalone_sender_fn=_standalone_send, max_message_length=0, emoji="💬", allow_update_command=True)
+ standalone_sender_fn=_standalone_send, max_message_length=0, emoji="💬", allow_update_command=True,
+ own_policy_env=("WEIXIN_DM_POLICY", "WEIXIN_GROUP_POLICY"),
+ )
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index 43b70fa91d7..e75e3b9a961 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -1239,4 +1239,5 @@ def register(ctx) -> None:
setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="WHATSAPP_ALLOWED_USERS",
allow_all_env="WHATSAPP_ALLOW_ALL_USERS", cron_deliver_env_var="WHATSAPP_HOME_CHANNEL",
standalone_sender_fn=_standalone_send, max_message_length=4096, emoji="💬", allow_update_command=True,
+ own_policy_env=("WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY"),
)
diff --git a/plugins/platforms/yuanbao/register.py b/plugins/platforms/yuanbao/register.py
index bcc12ece7a9..4c5f1968cc6 100644
--- a/plugins/platforms/yuanbao/register.py
+++ b/plugins/platforms/yuanbao/register.py
@@ -74,4 +74,6 @@ def register(ctx) -> None:
required_env=["YUANBAO_APP_ID", "YUANBAO_APP_SECRET"], install_hint=_INSTALL_HINT,
setup_fn=interactive_setup, allowed_users_env="YUANBAO_ALLOWED_USERS",
allow_all_env="YUANBAO_ALLOW_ALL_USERS", cron_deliver_env_var="YUANBAO_HOME_CHANNEL",
- standalone_sender_fn=_standalone_send, emoji="💎", allow_update_command=False)
+ standalone_sender_fn=_standalone_send, emoji="💎", allow_update_command=False,
+ own_policy_env=("YUANBAO_DM_POLICY", "YUANBAO_GROUP_POLICY"),
+ )
diff --git a/tests/gateway/test_platform_entry_authz_fields.py b/tests/gateway/test_platform_entry_authz_fields.py
new file mode 100644
index 00000000000..1dedd103a3c
--- /dev/null
+++ b/tests/gateway/test_platform_entry_authz_fields.py
@@ -0,0 +1,53 @@
+"""Bot-bypass and own-policy startup gates read the plugin's PlatformEntry, not a core table.
+
+A platform plugin that declares ``allow_bots_env`` / ``own_policy_env`` gets the same
+authorization and startup-abort behaviour core's bundled platforms do.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.session import SessionSource
+
+_NAME = "authzprobe"
+
+
+def probe_platform(monkeypatch):
+ from gateway.platform_registry import PlatformEntry, platform_registry
+
+ for var in ("AUTHZPROBE_ALLOW_BOTS", "AUTHZPROBE_DM_POLICY", "AUTHZPROBE_GROUP_POLICY",
+ "AUTHZPROBE_ALLOW_ALL_USERS", "GATEWAY_ALLOW_ALL_USERS", "GATEWAY_ALLOWED_USERS"):
+ monkeypatch.delenv(var, raising=False)
+ platform_registry.register(PlatformEntry(
+ name=_NAME, label="Authz Probe", adapter_factory=lambda cfg: None, check_fn=lambda: True,
+ allow_all_env="AUTHZPROBE_ALLOW_ALL_USERS", allow_bots_env="AUTHZPROBE_ALLOW_BOTS",
+ own_policy_env=("AUTHZPROBE_DM_POLICY", "AUTHZPROBE_GROUP_POLICY"),
+ ))
+ yield Platform(_NAME)
+ platform_registry.unregister(_NAME)
+
+
+def test_declared_allow_bots_env_admits_bot_without_user_id(probe_platform, monkeypatch):
+ from gateway.run import GatewayRunner
+
+ runner = object.__new__(GatewayRunner)
+ runner.pairing_store = SimpleNamespace(is_approved=lambda *_a, **_kw: False)
+ source = SessionSource(platform=probe_platform, chat_id="c1", chat_type="group", user_id=None,
+ user_name="", is_bot=True)
+ assert runner._is_user_authorized(source) is False
+ monkeypatch.setenv("AUTHZPROBE_ALLOW_BOTS", "all")
+ assert runner._is_user_authorized(source) is True
+
+
+def test_declared_own_policy_env_refuses_open_policy_without_allow_all(probe_platform, monkeypatch):
+ from gateway.run import _own_policy_open_startup_violation
+
+ cfg = GatewayConfig(platforms={probe_platform: PlatformConfig(enabled=True)})
+ assert _own_policy_open_startup_violation(cfg) is None
+ monkeypatch.setenv("AUTHZPROBE_GROUP_POLICY", "open")
+ assert _own_policy_open_startup_violation(cfg) == "authzprobe: open policy without allow-all opt-in"
+ monkeypatch.setenv("AUTHZPROBE_ALLOW_ALL_USERS", "true")
+ assert _own_policy_open_startup_violation(cfg) is None