Skip to content

The agent that grows with you

refactor(gateway): one OwnAccessPolicyMixin replaces five copied DM/group intake predicates

teknium18185834bc997
diff --git a/gateway/platforms/access_policy_mixin.py b/gateway/platforms/access_policy_mixin.py
new file mode 100644
index 00000000000..5f1bff27aac
--- /dev/null
+++ b/gateway/platforms/access_policy_mixin.py
@@ -0,0 +1,62 @@
+"""Config-driven DM / group intake policy shared by the adapters that gate access themselves
+(Weixin, WeCom, QQBot, WhatsApp, Yuanbao's ``AccessPolicy``).
+
+Host contract — the adapter sets these on ``self`` before any predicate runs: ``_dm_policy`` /
+``_group_policy`` (``open`` | ``allowlist`` | ``disabled`` | ``pairing``), ``_allow_from`` /
+``_group_allow_from`` (iterable of allowlist entries), and ``ALLOW_ALL_ENV_PREFIX`` (class
+attribute, e.g. ``"WEIXIN"``). Platform-specific allowlist matching goes through
+``_entry_matches``; env-seeded allowlists that must be re-read live go through
+``_live_dm_allow_from``.
+
+Every env read is profile-scoped and fails closed: under multiplexing ``os.environ`` holds the
+DEFAULT profile's opt-in, which must never open a secondary bot's DMs (#93522).
+"""
+
+from __future__ import annotations
+
+from typing import Iterable
+
+from gateway.platforms._shared import get_scoped_secret
+
+OPTIN_TRUTHY = frozenset({"true", "1", "yes"})
+
+
+class OwnAccessPolicyMixin:
+ ALLOW_ALL_ENV_PREFIX: str = ""
+
+ @property
+ def enforces_own_access_policy(self) -> bool:
+ return True
+
+ def _allow_all_env_names(self) -> tuple[str, ...]:
+ return ("GATEWAY_ALLOW_ALL_USERS", f"{self.ALLOW_ALL_ENV_PREFIX}_ALLOW_ALL_USERS")
+
+ def _open_dm_opted_in(self) -> bool:
+ return any(str(get_scoped_secret(name, "") or "").strip().lower() in OPTIN_TRUTHY
+ for name in self._allow_all_env_names())
+
+ def _entry_matches(self, entries: Iterable[str], target: str) -> bool:
+ return target in entries
+
+ def _live_dm_allow_from(self) -> Iterable[str]:
+ return self._allow_from
+
+ def _is_dm_allowed(self, sender_id: str) -> bool:
+ """Strict DM authorization — pairing does not imply access."""
+ if self._dm_policy == "allowlist":
+ return self._entry_matches(self._live_dm_allow_from(), sender_id)
+ return self._dm_policy == "open" and self._open_dm_opted_in()
+
+ def _is_dm_intake_allowed(self, sender_id: str) -> bool:
+ """Whether a DM may reach gateway intake; ``pairing`` admits everyone with a principal so the
+ handshake can run (the pairing gate itself runs later). A blank principal is never admitted."""
+ principal = str(sender_id or "").strip()
+ if not principal:
+ return False
+ return self._dm_policy == "pairing" or self._is_dm_allowed(principal)
+
+ def _is_group_allowed(self, chat_id: str, sender_id: str = "") -> bool:
+ """``disabled``/``pairing``/unknown policies never forward group traffic at intake."""
+ if self._group_policy == "allowlist":
+ return self._entry_matches(self._group_allow_from, chat_id)
+ return self._group_policy == "open"
diff --git a/gateway/platforms/qqbot/adapter.py b/gateway/platforms/qqbot/adapter.py
index 791f067a1fa..e3645900412 100644
--- a/gateway/platforms/qqbot/adapter.py
+++ b/gateway/platforms/qqbot/adapter.py
@@ -44,6 +44,7 @@ from gateway.platforms.base import (
)
from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms.helpers import strip_markdown
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
from gateway.platforms.media_cache import ext_for_mime
logger = logging.getLogger(__name__)
@@ -94,12 +95,13 @@ _STT_PROVIDER_BASE_URLS = {
_AUDIO_URL_EXTENSIONS = {".silk", ".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"}
-class QQAdapter(BasePlatformAdapter):
+class QQAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
"""QQ Bot adapter backed by the official QQ Bot WebSocket Gateway + REST API."""
# QQ Bot API does not support editing sent messages.
SUPPORTS_MESSAGE_EDITING = False
MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
+ ALLOW_ALL_ENV_PREFIX = "QQ"
_TYPING_INPUT_SECONDS = 60 # input_notify duration reported to QQ
_TYPING_DEBOUNCE_SECONDS = 50 # refresh before it expires
@@ -179,11 +181,6 @@ class QQAdapter(BasePlatformAdapter):
def name(self) -> str:
return "QQBot"
- @property
- def enforces_own_access_policy(self) -> bool:
- """QQBot gates DM/group access at intake via dm_policy/group_policy."""
- return True
-
# ── Connection lifecycle ──
async def connect(self, *, is_reconnect: bool = False) -> bool:
@@ -1660,35 +1657,7 @@ class QQAdapter(BasePlatformAdapter):
def _strip_at_mention(content: str) -> str:
return re.sub(r"^@\S+\s*", "", content.strip())
- def _open_dm_opted_in(self) -> bool:
- # Both names via the scoped reader: under multiplex os.environ is the DEFAULT profile's
- # opt-in, which must not open a secondary bot's DMs.
- truthy = {"true", "1", "yes"}
- return any(_resolve_qq_secret(name, "").lower() in truthy
- for name in ("GATEWAY_ALLOW_ALL_USERS", "QQ_ALLOW_ALL_USERS"))
-
- def _is_dm_allowed(self, user_id: str) -> bool:
- if self._dm_policy == "allowlist":
- return self._entry_matches(self._allow_from, user_id)
- if self._dm_policy == "open":
- return self._open_dm_opted_in()
- return False
-
- def _is_dm_intake_allowed(self, user_id: str) -> bool:
- principal = str(user_id or "").strip()
- if not principal:
- return False
- if self._dm_policy == "pairing":
- return True
- return self._is_dm_allowed(principal)
-
- def _is_group_allowed(self, group_id: str, user_id: str) -> bool:
- if self._group_policy == "allowlist":
- return self._entry_matches(self._group_allow_from, group_id)
- return self._group_policy == "open"
-
- @staticmethod
- def _entry_matches(entries: List[str], target: str) -> bool:
+ def _entry_matches(self, entries: List[str], target: str) -> bool:
normalized_target = str(target).strip().lower()
return any(str(e).strip().lower() in ("*", normalized_target) for e in entries)
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index aeda977dbdb..2c39d4ef0fe 100644
--- a/gateway/platforms/weixin.py
+++ b/gateway/platforms/weixin.py
@@ -29,6 +29,7 @@ CRYPTO_AVAILABLE = Cipher is not None
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import MessageDeduplicator, greedy_pack_blocks
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
from gateway.platforms.base import (
_IMAGE_EXTS, _VIDEO_EXTS, gateway_trust_env, BasePlatformAdapter, SendResult,
cache_audio_from_bytes_async, cache_document_from_bytes_async, cache_image_from_bytes_async,
@@ -691,7 +692,8 @@ _OUTBOUND_BY_EXT: Tuple[Tuple[frozenset, str, str], ...] = (
_DIRECT_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
-class WeixinAdapter(BasePlatformAdapter):
+class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
+ ALLOW_ALL_ENV_PREFIX = "WEIXIN"
supports_code_blocks = True # Weixin renders fenced code blocks
splits_long_messages = True # send() chunks via _split_text()
MAX_MESSAGE_LENGTH = 2000
@@ -893,7 +895,7 @@ class WeixinAdapter(BasePlatformAdapter):
return
chat_type, effective_chat_id = _guess_chat_type(message, self._account_id)
if chat_type == "group":
- if self._group_policy in {"disabled", "pairing"} or (self._group_policy == "allowlist" and effective_chat_id not in self._group_allow_from):
+ if not self._is_group_allowed(effective_chat_id):
return
elif not self._is_dm_intake_allowed(sender_id):
return
@@ -919,24 +921,6 @@ class WeixinAdapter(BasePlatformAdapter):
else:
await self.handle_message(event)
- def _open_dm_opted_in(self) -> bool:
- # Scoped reads: the default profile's allow-all flag must not leak into a multiplexed secondary profile's gate.
- return any((_wx_secret(name, "") or "").lower() in {"true", "1", "yes"} for name in ("GATEWAY_ALLOW_ALL_USERS", "WEIXIN_ALLOW_ALL_USERS"))
-
- def _is_dm_allowed(self, sender_id: str) -> bool:
- if self._dm_policy == "allowlist":
- return sender_id in self._allow_from
- return self._dm_policy == "open" and self._open_dm_opted_in()
-
- def _is_dm_intake_allowed(self, sender_id: str) -> bool:
- """Like ``_is_dm_allowed`` but ``pairing`` admits everyone at intake (pairing gate runs later)."""
- return self._dm_policy == "pairing" or self._is_dm_allowed(sender_id)
-
- @property
- def enforces_own_access_policy(self) -> bool:
- """Weixin gates DM/group access at intake via dm_policy/group_policy."""
- return True
-
def _text_batch_key(self, event: MessageEvent) -> str:
from gateway.session import build_session_key
return build_session_key(
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.py
index f51e19ad300..ee22eaa6c56 100644
--- a/gateway/platforms/whatsapp_cloud.py
+++ b/gateway/platforms/whatsapp_cloud.py
@@ -41,7 +41,8 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, ExecApprovalPrompt, SendResult
from gateway.platforms.event import MessageEvent, MessageType
-from gateway.platforms.whatsapp_common import _OPTIN_TRUTHY, WhatsAppBehaviorMixin, _get_wsecret
+from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin, _get_wsecret
+from gateway.platforms.access_policy_mixin import OPTIN_TRUTHY as _OPTIN_TRUTHY
from gateway.platforms.media_cache import ext_for_mime
from gateway import rich_sent_store
from hermes_constants import get_hermes_dir
@@ -246,9 +247,9 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
return (bare or sender_id) in self._normalize_allow_ids(self._live_dm_allow_from())
return super()._is_dm_allowed(sender_id)
- def _open_dm_opted_in(self) -> bool:
+ def _allow_all_env_names(self) -> tuple[str, ...]:
"""Also honor the documented WHATSAPP_CLOUD_ALLOW_ALL_USERS opt-in."""
- return _cloud_allow_all_opted_in() or super()._open_dm_opted_in()
+ return (*super()._allow_all_env_names(), "WHATSAPP_CLOUD_ALLOW_ALL_USERS")
# ------------------------------------------------------------------ lifecycle
async def connect(self, *, is_reconnect: bool = False) -> bool:
diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.py
index dacc3255c06..ef202be5fcb 100644
--- a/gateway/platforms/whatsapp_common.py
+++ b/gateway/platforms/whatsapp_common.py
@@ -19,12 +19,12 @@ from pathlib import Path
from typing import Any, Dict, Optional
from gateway.platforms._shared import get_scoped_secret as _get_wsecret
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
logger = logging.getLogger(__name__)
_TRUTHY = {"true", "1", "yes", "on"}
-_OPTIN_TRUTHY = {"true", "1", "yes"}
def _stash(pattern: str, text: str, tag: str) -> tuple[str, list[str]]:
@@ -47,12 +47,13 @@ def _header_to_bold(m: re.Match) -> str:
return f"*{inner}*"
-class WhatsAppBehaviorMixin:
+class WhatsAppBehaviorMixin(OwnAccessPolicyMixin):
"""Shared behavior for all WhatsApp adapters (Baileys + Cloud API); owns no state
of its own — see the module docstring for the host adapter's attribute contract."""
# Practical UX limit, not the ~65K protocol max (long messages are unreadable on mobile).
MAX_MESSAGE_LENGTH: int = 4096
+ ALLOW_ALL_ENV_PREFIX = "WHATSAPP"
supports_code_blocks = True # WhatsApp renders fenced code blocks (monospace)
DEFAULT_REPLY_PREFIX: str = "☤ *Hermes Agent*\n────────────\n"
@@ -68,11 +69,6 @@ class WhatsAppBehaviorMixin:
return content
return cls._OUTBOUND_ODD_SPACE_RE.sub(" ", cls._OUTBOUND_INVISIBLE_CHARS_RE.sub("", content))
- @property
- def enforces_own_access_policy(self) -> bool:
- """WhatsApp gates DM/group access at intake via dm_policy/group_policy."""
- return True
-
def _effective_reply_prefix(self) -> str:
"""Prefix for outgoing replies in self-chat mode (Cloud API overrides to ``""``)."""
if (_get_wsecret("WHATSAPP_MODE", default="self-chat") or "self-chat") != "self-chat":
@@ -156,12 +152,6 @@ class WhatsAppBehaviorMixin:
return cid == "status@broadcast" or cid.endswith(("@broadcast", "@newsletter"))
# ------------------------------------------------------------------ gating
- def _open_dm_opted_in(self) -> bool:
- # Both names via the scoped reader — the DEFAULT profile's os.environ opt-in must not open
- # a secondary bot's DMs.
- return any((_get_wsecret(name, default="") or "").lower() in _OPTIN_TRUTHY
- for name in ("GATEWAY_ALLOW_ALL_USERS", "WHATSAPP_ALLOW_ALL_USERS"))
-
@staticmethod
def _matches_whatsapp_allowlist(candidate: str, allow_from) -> bool:
"""Match a WhatsApp identifier against an allowlist across phone/LID forms. Inbound senders
@@ -182,28 +172,8 @@ class WhatsAppBehaviorMixin:
for entry in allow_from
)
- def _is_dm_allowed(self, sender_id: str) -> bool:
- """Strict DM authorization — pairing does not imply access."""
- if self._dm_policy == "allowlist":
- return self._matches_whatsapp_allowlist(sender_id, self._live_dm_allow_from())
- return self._dm_policy == "open" and self._open_dm_opted_in()
-
- def _is_dm_intake_allowed(self, sender_id: str) -> bool:
- """Whether a DM may reach the gateway intake (pairing handshake path)."""
- principal = str(sender_id or "").strip()
- if not principal:
- return False
- if self._dm_policy == "allowlist":
- return self._matches_whatsapp_allowlist(principal, self._live_dm_allow_from())
- if self._dm_policy == "pairing":
- return True
- return self._dm_policy == "open" and self._open_dm_opted_in()
-
- def _is_group_allowed(self, chat_id: str) -> bool:
- """Check whether a group chat should be processed."""
- if self._group_policy == "allowlist":
- return self._matches_whatsapp_allowlist(chat_id, self._group_allow_from)
- return self._group_policy == "open"
+ def _entry_matches(self, entries, target: str) -> bool:
+ return self._matches_whatsapp_allowlist(target, entries)
def _compile_mention_patterns(self):
patterns = self.config.extra.get("mention_patterns")
diff --git a/gateway/platforms/yuanbao.py b/gateway/platforms/yuanbao.py
index 05a3c8e70e3..59acc4ec407 100644
--- a/gateway/platforms/yuanbao.py
+++ b/gateway/platforms/yuanbao.py
@@ -50,6 +50,7 @@ from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms import helpers as _mdchunk
from gateway.platforms._shared import get_scoped_secret as _yb_secret, profile_scoped as _profile_scoped
from gateway.platforms.helpers import MessageDeduplicator
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
from gateway.platforms.yuanbao_media import (
download_url as media_download_url, get_cos_credentials, upload_to_cos,
build_image_msg_body, build_file_msg_body, guess_mime_type, md5_hex,
@@ -700,39 +701,30 @@ class ChatRoutingMiddleware(InboundMiddleware):
await next_fn()
-class AccessPolicy:
+class AccessPolicy(OwnAccessPolicyMixin):
"""DM / group access rules shared by inbound middleware and outbound ``send_dm``."""
+ ALLOW_ALL_ENV_PREFIX = "YUANBAO"
+
def __init__(self, dm_policy: str, dm_allow_from: list[str], group_policy: str, group_allow_from: list[str]) -> None:
self._dm_policy = dm_policy
- self._dm_allow_from = dm_allow_from
+ self._allow_from = dm_allow_from
self._group_policy = group_policy
self._group_allow_from = group_allow_from
- def _open_dm_opted_in(self) -> bool:
- return any((_yb_secret(k, "") or "").lower() in {"true", "1", "yes"}
- for k in ("GATEWAY_ALLOW_ALL_USERS", "YUANBAO_ALLOW_ALL_USERS"))
-
- def _evaluate(self, policy: str, allow_from: list[str], principal: str, *, pairing: bool) -> bool:
- """Shared allow/deny rule; *pairing* is the verdict for the "pairing" policy."""
- if policy == "allowlist":
- return principal in allow_from
- if policy == "pairing":
- return pairing
- if policy == "open":
- return self._open_dm_opted_in()
- return False # "disabled" or unknown
-
def is_dm_allowed(self, sender_id: str) -> bool:
"""Strict DM authorization — pairing does not imply access."""
- return self._evaluate(self._dm_policy, self._dm_allow_from, sender_id.strip(), pairing=False)
+ return self._is_dm_allowed(sender_id.strip())
def is_dm_intake_allowed(self, sender_id: str) -> bool:
"""Whether a DM may reach gateway intake (pairing handshake path)."""
- principal = str(sender_id or "").strip()
- return bool(principal) and self._evaluate(self._dm_policy, self._dm_allow_from, principal, pairing=True)
+ return self._is_dm_intake_allowed(sender_id)
def is_group_allowed(self, group_code: str) -> bool:
- return self._evaluate(self._group_policy, self._group_allow_from, group_code.strip(), pairing=False)
+ """Unlike the shared rule, an ``open`` group still needs the allow-all opt-in: Yuanbao groups
+ have no runner-side mention gate, so open-without-opt-in would forward every member."""
+ if self._group_policy == "open":
+ return self._open_dm_opted_in()
+ return self._is_group_allowed(group_code.strip())
@property
def dm_policy(self) -> str:
@@ -2681,7 +2673,7 @@ class YuanbaoAdapter(BasePlatformAdapter):
@property
def enforces_own_access_policy(self) -> bool:
- """Yuanbao gates DM/group access at intake via dm_policy/group_policy."""
+ """Intake gating lives in ``AccessPolicy`` (composed, not inherited), so the flag stays here."""
return True
def _sender_may_designate_home(self, ctx: InboundContext) -> bool:
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index dbc0f29429e..218d949b16a 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -28,6 +28,7 @@ HTTPX_AVAILABLE = httpx is not None
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import MessageDeduplicator
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
from gateway.platforms.event import MessageEvent, MessageType
from utils import env_float
@@ -109,7 +110,7 @@ def _bounded_put(store: Dict[str, str], key: str, value: str) -> bool:
return True
-class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePlatformAdapter):
+class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccessPolicyMixin, BasePlatformAdapter):
"""WeCom AI Bot adapter backed by a persistent WebSocket connection."""
MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
@@ -532,26 +533,12 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
return MessageType.VOICE
return MessageType.TEXT
- @property
- def enforces_own_access_policy(self) -> bool:
- """WeCom gates DM/group access at intake via dm_policy/group_policy."""
- return True
-
- def _open_dm_opted_in(self) -> bool:
- # Scoped reads: default profile's allow-all flag must not leak into a multiplexed profile.
- return any((_get_scoped_secret(var, "") or "").lower() in {"true", "1", "yes"} for var in ("GATEWAY_ALLOW_ALL_USERS", "WECOM_ALLOW_ALL_USERS"))
-
- def _is_dm_allowed(self, sender_id: str) -> bool:
- if self._dm_policy == "allowlist":
- return _entry_matches(self._allow_from, sender_id)
- return self._dm_policy == "open" and self._open_dm_opted_in()
-
- def _is_dm_intake_allowed(self, sender_id: str) -> bool:
- principal = str(sender_id or "").strip()
- return bool(principal) and (self._dm_policy == "pairing" or self._is_dm_allowed(principal))
+ def _entry_matches(self, entries: List[str], target: str) -> bool:
+ return _entry_matches(entries, target)
def _is_group_allowed(self, chat_id: str, sender_id: str) -> bool:
- if self._group_policy in ("disabled", "pairing") or (self._group_policy == "allowlist" and not _entry_matches(self._group_allow_from, chat_id)):
+ """Per-group ``groups.<id>.allow_from`` restricts senders on top of the chat-level policy."""
+ if not super()._is_group_allowed(chat_id):
return False
group_cfg = self._resolve_group_cfg(chat_id)
sender_allow = _coerce_list(group_cfg.get("allow_from") or group_cfg.get("allowFrom"))
diff --git a/tests/gateway/test_access_policy_mixin.py b/tests/gateway/test_access_policy_mixin.py
new file mode 100644
index 00000000000..54edaa7d40b
--- /dev/null
+++ b/tests/gateway/test_access_policy_mixin.py
@@ -0,0 +1,91 @@
+"""Every own-policy adapter must reach the same allow/deny verdict for the same policy inputs.
+
+The predicates used to be five hand-copied bodies (weixin, wecom, qqbot, whatsapp, yuanbao) that
+drifted on blank principals and scoped env reads; ``OwnAccessPolicyMixin`` is the single rule.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import itertools
+
+import pytest
+
+from agent.secret_scope import reset_secret_scope, set_secret_scope
+from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
+
+POLICIES = ("open", "allowlist", "disabled", "pairing", "typo")
+SENDERS = ("alice", "stranger", "", " ", None)
+
+
+def _scope(secrets):
+ token = set_secret_scope(secrets)
+ try:
+ yield
+ finally:
+ reset_secret_scope(token)
+
+
+def _hosts():
+ """One bare instance per own-policy class, attributes set exactly as the adapters do."""
+ from gateway.platforms.qqbot.adapter import QQAdapter
+ from gateway.platforms.weixin import WeixinAdapter
+ from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
+ from gateway.platforms.yuanbao import AccessPolicy
+ from plugins.platforms.wecom.adapter import WeComAdapter
+
+ hosts = {
+ "weixin": object.__new__(WeixinAdapter),
+ "wecom": object.__new__(WeComAdapter),
+ "qqbot": object.__new__(QQAdapter),
+ "whatsapp": WhatsAppBehaviorMixin(),
+ "yuanbao": AccessPolicy("open", [], "open", []),
+ }
+ hosts["whatsapp"]._dm_allowlist_source = "config"
+ hosts["wecom"]._groups = {}
+ return hosts
+
+
+def _verdicts(host, name, dm_policy, group_policy):
+ host._dm_policy, host._group_policy = dm_policy, group_policy
+ host._allow_from, host._group_allow_from = ["alice"], ["room-1"]
+ out = {}
+ for sender in SENDERS:
+ out[("dm", sender)] = host._is_dm_allowed(sender or "")
+ out[("intake", sender)] = host._is_dm_intake_allowed(sender)
+ for group in ("room-1", "room-2"):
+ args = (group, "alice") if name in ("wecom", "qqbot") else (group,)
+ out[("group", group)] = host._is_group_allowed(*args)
+ return out
+
+
[email protected]("opt_in", [{}, {"GATEWAY_ALLOW_ALL_USERS": "true"}])
+def test_all_own_policy_adapters_agree(monkeypatch, opt_in):
+ for var in ("GATEWAY_ALLOW_ALL_USERS", "WEIXIN_ALLOW_ALL_USERS", "WECOM_ALLOW_ALL_USERS",
+ "QQ_ALLOW_ALL_USERS", "WHATSAPP_ALLOW_ALL_USERS", "YUANBAO_ALLOW_ALL_USERS"):
+ monkeypatch.delenv(var, raising=False)
+ hosts = _hosts()
+ with _scope(opt_in):
+ for dm_policy, group_policy in itertools.product(POLICIES, POLICIES):
+ table = {name: _verdicts(host, name, dm_policy, group_policy) for name, host in hosts.items()}
+ for name, verdicts in table.items():
+ assert verdicts == table["weixin"], (name, dm_policy, group_policy, opt_in)
+ expected_open = bool(opt_in) and dm_policy == "open"
+ assert table["weixin"][("dm", "stranger")] is expected_open
+ assert table["weixin"][("intake", " ")] is False # blank principal never admitted
+ assert table["weixin"][("intake", "stranger")] is (dm_policy == "pairing" or expected_open)
+
+
+def test_platform_prefix_env_name_is_scoped_and_fail_closed(monkeypatch):
+ class Host(OwnAccessPolicyMixin):
+ ALLOW_ALL_ENV_PREFIX = "DEMO"
+ _dm_policy, _group_policy, _allow_from, _group_allow_from = "open", "open", [], []
+
+ monkeypatch.setattr("agent.secret_scope._MULTIPLEX_ACTIVE", True)
+ monkeypatch.setenv("DEMO_ALLOW_ALL_USERS", "true") # the DEFAULT profile's opt-in
+ assert Host()._allow_all_env_names() == ("GATEWAY_ALLOW_ALL_USERS", "DEMO_ALLOW_ALL_USERS")
+ with _scope({}): # secondary profile: scope installed, key absent
+ assert Host()._is_dm_allowed("anyone") is False
+ with _scope({"DEMO_ALLOW_ALL_USERS": "yes"}):
+ assert Host()._is_dm_allowed("anyone") is True
diff --git a/tests/gateway/test_adapter_authz_secret_scope.py b/tests/gateway/test_adapter_authz_secret_scope.py
index 3444246b889..9eac612b2e4 100644
--- a/tests/gateway/test_adapter_authz_secret_scope.py
+++ b/tests/gateway/test_adapter_authz_secret_scope.py
@@ -52,8 +52,9 @@ def _matrix(extra=None):
def _whatsapp():
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
- return SimpleNamespace(_dm_allowlist_source="WHATSAPP_ALLOWED_USERS", _allow_from=set(),
- _coerce_allow_list=WhatsAppBehaviorMixin._coerce_allow_list)
+ host = WhatsAppBehaviorMixin()
+ host._dm_allowlist_source, host._allow_from = "WHATSAPP_ALLOWED_USERS", set()
+ return host
def _slack():
@@ -87,7 +88,7 @@ _GATES = [
lambda: __import__("plugins.platforms.email.adapter", fromlist=["EmailAdapter"]).EmailAdapter._allowlist_in_effect(),
False, True),
("qqbot.open_dm", {"QQ_ALLOW_ALL_USERS": "true"},
- lambda: __import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter._open_dm_opted_in(SimpleNamespace()),
+ lambda: __import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter._open_dm_opted_in(object.__new__(__import__("gateway.platforms.qqbot.adapter", fromlist=["QQAdapter"]).QQAdapter)),
False, True),
("whatsapp.open_dm", {"GATEWAY_ALLOW_ALL_USERS": "true"},
lambda: __import__("gateway.platforms.whatsapp_common", fromlist=["WhatsAppBehaviorMixin"]).WhatsAppBehaviorMixin._open_dm_opted_in(_whatsapp()),
diff --git a/tests/gateway/test_yuanbao_secret_scope.py b/tests/gateway/test_yuanbao_secret_scope.py
index 8617f5edd47..0e662280f0b 100644
--- a/tests/gateway/test_yuanbao_secret_scope.py
+++ b/tests/gateway/test_yuanbao_secret_scope.py
@@ -35,7 +35,7 @@ class TestYuanbaoAdapterAuthzScope:
finally:
secret_scope.reset_secret_scope(token)
assert adapter._access_policy._dm_policy == "allowlist"
- assert adapter._access_policy._dm_allow_from == ["scoped-user"]
+ assert adapter._access_policy._allow_from == ["scoped-user"]
def test_scoped_miss_does_not_admit_default_profiles_allowlist(self, multiplex_on, monkeypatch):
monkeypatch.setenv("YUANBAO_DM_POLICY", "allowlist")
@@ -46,7 +46,7 @@ class TestYuanbaoAdapterAuthzScope:
finally:
secret_scope.reset_secret_scope(token)
assert adapter._access_policy._dm_policy == "pairing"
- assert adapter._access_policy._dm_allow_from == []
+ assert adapter._access_policy._allow_from == []
class TestYuanbaoAccessPolicyOpenDmOptIn: