The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve WhatsApp allowlist config precedence on live checks
fangliquanflq810c8777e152
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex 8659ed69694..41b815088da 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -255,15 +255,24 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._reply_prefix: Optional[str] = extra.get("reply_prefix")# Allowlist: honor the *documented* WHATSAPP_CLOUD_ALLOWED_USERS (the# var the setup wizard writes) in addition to WHATSAPP_CLOUD_ALLOW_FROM.- # The adapter historically read only ALLOW_FROM, so an allowlist- # configured via the documented var silently dropped every inbound.+ # Precedence matches construction forever: explicit config, then legacy+ # ALLOW_FROM, then ALLOWED_USERS. Track the winning source so live DM+ # checks do not let a lower-precedence env broaden access.+ explicit_allow = extra.get("allow_from") or extra.get("allowFrom")+ if explicit_allow:+ self._dm_allowlist_source = "config"+ allow_raw = explicit_allow+ elif os.getenv("WHATSAPP_CLOUD_ALLOW_FROM"):+ self._dm_allowlist_source = "WHATSAPP_CLOUD_ALLOW_FROM"+ allow_raw = os.getenv("WHATSAPP_CLOUD_ALLOW_FROM")+ elif os.getenv("WHATSAPP_CLOUD_ALLOWED_USERS"):+ self._dm_allowlist_source = "WHATSAPP_CLOUD_ALLOWED_USERS"+ allow_raw = os.getenv("WHATSAPP_CLOUD_ALLOWED_USERS")+ else:+ self._dm_allowlist_source = None+ allow_raw = Noneself._allow_from: set[str] = self._normalize_allow_ids(- self._coerce_allow_list(- extra.get("allow_from")- or extra.get("allowFrom")- or os.getenv("WHATSAPP_CLOUD_ALLOW_FROM")- or os.getenv("WHATSAPP_CLOUD_ALLOWED_USERS")- )+ self._coerce_allow_list(allow_raw))# DM policy: explicit config wins; otherwise choose a safe, working# default -- "open" if the operator opted into allow-all, else@@ -385,10 +394,6 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):normalized.add(digits or entry)return normalized- def _dm_allowlist_env_keys(self) -> tuple[str, ...]:- """Cloud pairing mirrors WHATSAPP_CLOUD_ALLOWED_USERS (then legacy ALLOW_FROM)."""- return ("WHATSAPP_CLOUD_ALLOWED_USERS", "WHATSAPP_CLOUD_ALLOW_FROM")-def _is_dm_allowed(self, sender_id: str) -> bool:"""Allowlist check against the normalized bare wa_id."""if self._dm_policy == "allowlist":diff --git a/gateway/platforms/whatsapp_common.py b/gateway/platforms/whatsapp_common.pyindex 9032bff1d7a..04b64eed06a 100644--- a/gateway/platforms/whatsapp_common.py+++ b/gateway/platforms/whatsapp_common.py@@ -134,27 +134,21 @@ class WhatsAppBehaviorMixin:return {str(part).strip() for part in raw if str(part).strip()}return {part.strip() for part in str(raw).split(",") if part.strip()}- def _dm_allowlist_env_keys(self) -> tuple[str, ...]:- """Env vars that carry the live DM allowlist for this adapter.-- Pairing approve/revoke mutates the documented ``*_ALLOWED_USERS`` var- in-process. Intake must prefer that live carrier over the construction- snapshot in ``_allow_from`` so sole-entry revocation takes effect- without a gateway restart.- """- return ("WHATSAPP_ALLOWED_USERS",)-def _live_dm_allow_from(self) -> set[str]:"""Allowlist currently enforced for DM intake / strict DM auth.- When a pairing-synced env allowlist key is present in ``os.environ``,- that value is authoritative (including the empty set after the last- entry is cleared but before the key is removed). Otherwise fall back- to the adapter snapshot seeded at construction from config/env.+ Source precedence matches construction: explicit config wins over any+ env carrier. When the adapter was seeded from an env var, re-read that+ same key so pairing approve/revoke takes effect without restart+ (including an empty value while the key is still present). Config-seeded+ adapters keep the in-memory snapshot, which pairing revoke purges in+ place — a lower-precedence or stale env value must not broaden access."""- for key in self._dm_allowlist_env_keys():- if key in os.environ:- return self._coerce_allow_list(os.environ.get(key, ""))+ source = getattr(self, "_dm_allowlist_source", None)+ if isinstance(source, str) and source != "config":+ if source in os.environ:+ return self._coerce_allow_list(os.environ.get(source, ""))+ return set(self._allow_from or ())return set(self._allow_from or ())# ------------------------------------------------------------------ JID helpersdiff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.pyindex 512dc932627..0254d5f4d07 100644--- a/plugins/platforms/whatsapp/adapter.py+++ b/plugins/platforms/whatsapp/adapter.py@@ -409,13 +409,19 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):self._reply_prefix: Optional[str] = config.extra.get("reply_prefix")self._dm_policy = str(config.extra.get("dm_policy") or os.getenv("WHATSAPP_DM_POLICY", "pairing")).strip().lower()# Prefer config.extra, then the documented WHATSAPP_ALLOWED_USERS env- # (setup wizard / pairing mirror). Construction seeds the snapshot;- # intake re-reads the live env via ``_live_dm_allow_from``.- self._allow_from = self._coerce_allow_list(- config.extra.get("allow_from")- or config.extra.get("allowFrom")- or os.getenv("WHATSAPP_ALLOWED_USERS")- )+ # (setup wizard / pairing mirror). Track which source won so live DM+ # checks preserve that precedence (env must not override explicit config).+ explicit_allow = config.extra.get("allow_from") or config.extra.get("allowFrom")+ if explicit_allow:+ self._dm_allowlist_source = "config"+ allow_raw = explicit_allow+ elif os.getenv("WHATSAPP_ALLOWED_USERS"):+ self._dm_allowlist_source = "WHATSAPP_ALLOWED_USERS"+ allow_raw = os.getenv("WHATSAPP_ALLOWED_USERS")+ else:+ self._dm_allowlist_source = None+ allow_raw = None+ self._allow_from = self._coerce_allow_list(allow_raw)self._group_policy = str(config.extra.get("group_policy") or os.getenv("WHATSAPP_GROUP_POLICY", "pairing")).strip().lower()self._group_allow_from = self._coerce_allow_list(config.extra.get("group_allow_from") or config.extra.get("groupAllowFrom"))read_receipts = config.extra.get("send_read_receipts", False)diff --git a/tests/gateway/test_pairing_allowlist_bypass.py b/tests/gateway/test_pairing_allowlist_bypass.pyindex 62b1df5dbc7..9487fd5ba2e 100644--- a/tests/gateway/test_pairing_allowlist_bypass.py+++ b/tests/gateway/test_pairing_allowlist_bypass.py@@ -230,6 +230,7 @@ def test_revoke_whatsapp_sole_entry_denies_live_adapter_without_restart()self.platform = Platform.WHATSAPPself._dm_policy = "allowlist"+ self._dm_allowlist_source = "config"self._allow_from = {"15551234567"}self._group_policy = "pairing"self._group_allow_from = set()@@ -277,3 +278,55 @@ def test_revoke_whatsapp_sole_entry_denies_live_adapter_without_restart(chat_type="dm",)) is False+++def test_whatsapp_live_allowlist_keeps_explicit_config_over_env(monkeypatch):+ """Explicit allow_from must stay authoritative when env differs.++ Live DM checks must not invert construction precedence: a stale or+ lower-precedence WHATSAPP_ALLOWED_USERS entry must not authorize (or+ replace) an explicit config allowlist.+ """+ from gateway.config import PlatformConfig+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter++ monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "15550000002")+ adapter = WhatsAppAdapter(+ PlatformConfig(+ enabled=True,+ extra={+ "dm_policy": "allowlist",+ "allow_from": ["15550000001"],+ },+ )+ )++ assert adapter._dm_allowlist_source == "config"+ assert adapter._is_dm_intake_allowed("15550000001") is True+ assert adapter._is_dm_allowed("15550000001") is True+ assert adapter._is_dm_intake_allowed("15550000002") is False+ assert adapter._is_dm_allowed("15550000002") is False++ # Pairing-style env mutation must not broaden a config-seeded allowlist.+ monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "15550000002,15550000003")+ assert adapter._is_dm_intake_allowed("15550000001") is True+ assert adapter._is_dm_intake_allowed("15550000002") is False+ assert adapter._is_dm_intake_allowed("15550000003") is False+++def test_whatsapp_live_allowlist_rereads_env_when_env_seeded(monkeypatch):+ """Env-seeded adapters still pick up pairing allowlist mutations live."""+ from gateway.config import PlatformConfig+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter++ monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "15551234567")+ adapter = WhatsAppAdapter(+ PlatformConfig(enabled=True, extra={"dm_policy": "allowlist"})+ )++ assert adapter._dm_allowlist_source == "WHATSAPP_ALLOWED_USERS"+ assert adapter._is_dm_intake_allowed("15551234567") is True++ monkeypatch.setenv("WHATSAPP_ALLOWED_USERS", "")+ assert adapter._is_dm_intake_allowed("15551234567") is False+ assert adapter._is_dm_allowed("15551234567") is Falsediff --git a/tests/gateway/test_whatsapp_cloud_allowed_users.py b/tests/gateway/test_whatsapp_cloud_allowed_users.pyindex f881d68471d..6c665b575b9 100644--- a/tests/gateway/test_whatsapp_cloud_allowed_users.py+++ b/tests/gateway/test_whatsapp_cloud_allowed_users.py@@ -73,3 +73,44 @@ def test_allow_from_still_takes_precedence(monkeypatch):# Legacy ALLOW_FROM wins when both are set (documented precedence).assert "15550000001" in adapter._allow_fromassert "15559999999" not in adapter._allow_from+ assert adapter._dm_allowlist_source == "WHATSAPP_CLOUD_ALLOW_FROM"+ assert adapter._is_dm_allowed("15550000001") is True+ assert adapter._is_dm_allowed("15559999999") is False+++def test_explicit_config_beats_cloud_env_on_live_checks(monkeypatch):+ """Live DM auth must keep explicit config above both cloud env carriers."""+ adapter = _build_adapter(+ monkeypatch,+ {+ "WHATSAPP_CLOUD_ALLOW_FROM": "15550000002",+ "WHATSAPP_CLOUD_ALLOWED_USERS": "15550000003",+ },+ extra={"dm_policy": "allowlist", "allow_from": ["15550000001"]},+ )++ assert adapter._dm_allowlist_source == "config"+ assert adapter._is_dm_allowed("15550000001") is True+ assert adapter._is_dm_intake_allowed("15550000001") is True+ assert adapter._is_dm_allowed("15550000002") is False+ assert adapter._is_dm_allowed("15550000003") is False+ assert adapter._is_dm_intake_allowed("15550000002") is False++ # Mutating lower-precedence env must not replace the config allowlist.+ monkeypatch.setenv("WHATSAPP_CLOUD_ALLOWED_USERS", "15550000003,15550000004")+ assert adapter._is_dm_allowed("15550000001") is True+ assert adapter._is_dm_allowed("15550000003") is False+ assert adapter._is_dm_allowed("15550000004") is False+++def test_cloud_allowed_users_live_reread_when_env_seeded(monkeypatch):+ adapter = _build_adapter(+ monkeypatch,+ {"WHATSAPP_CLOUD_ALLOWED_USERS": "15551234567"},+ )++ assert adapter._dm_allowlist_source == "WHATSAPP_CLOUD_ALLOWED_USERS"+ assert adapter._is_dm_allowed("15551234567") is True++ monkeypatch.setenv("WHATSAPP_CLOUD_ALLOWED_USERS", "")+ assert adapter._is_dm_allowed("15551234567") is False