The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(whatsapp): bind cloud webhooks to configured identity
FroRaut4152c69636a2
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.pyindex cfcf5e52202..47631f69c1a 100644--- a/gateway/platforms/whatsapp_cloud.py+++ b/gateway/platforms/whatsapp_cloud.py@@ -247,6 +247,16 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):bare = re.sub(r"\D", "", str(target).split("@", 1)[0]) or targetreturn bare in self._normalize_allow_ids(entries) or super()._entry_matches(entries, target)+ def _webhook_identity_matches(self, entry_id: Any, metadata: Any) -> bool:+ """Bind a signed callback to this adapter's configured Meta identities."""+ metadata = metadata if isinstance(metadata, dict) else {}+ incoming_phone_number_id = str(metadata.get("phone_number_id") or "").strip()+ incoming_waba_id = str(entry_id or "").strip()+ return (+ (not self._phone_number_id or incoming_phone_number_id == self._phone_number_id)+ and (not self._waba_id or incoming_waba_id == self._waba_id)+ )+def _allow_all_env_names(self) -> tuple[str, ...]:"""Also honor the documented WHATSAPP_CLOUD_ALLOW_ALL_USERS opt-in."""return (*super()._allow_all_env_names(), "WHATSAPP_CLOUD_ALLOW_ALL_USERS")@@ -765,6 +775,14 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):if not isinstance(change, dict) or change.get("field") != "messages":continue # account_alerts, template_status_update, … — not message ingressvalue = change.get("value") or {}+ if not isinstance(value, dict) or not self._webhook_identity_matches(+ entry.get("id"), value.get("metadata")+ ):+ logger.warning(+ "[whatsapp_cloud] ignoring signed webhook whose WABA or phone-number identity "+ "does not match this adapter"+ )+ continuecontacts_by_waid = {wa_id: str((contact.get("profile") or {}).get("name") or "").strip()for contact in value.get("contacts") or []diff --git a/hermes_cli/setup_whatsapp_cloud.py b/hermes_cli/setup_whatsapp_cloud.pyindex b507a9121d4..b0308a69fa6 100644--- a/hermes_cli/setup_whatsapp_cloud.py+++ b/hermes_cli/setup_whatsapp_cloud.py@@ -208,7 +208,7 @@ _OPTIONAL_ID_STEPS = ("WhatsApp Business Account ID. Found in: App Dashboard →\n""WhatsApp → API Setup, near the top — 'WhatsApp Business\n""Account ID'. Numeric, ~15+ digits.\n"- "Not required for messaging — useful for analytics."))+ "When set, inbound webhooks must match this business account."))def _credential_step(step) -> bool:diff --git a/tests/gateway/test_whatsapp_cloud.py b/tests/gateway/test_whatsapp_cloud.pyindex 06dcd7a254a..a69b358cdd8 100644--- a/tests/gateway/test_whatsapp_cloud.py+++ b/tests/gateway/test_whatsapp_cloud.py@@ -52,11 +52,11 @@ def _make_adapter(**overrides):adapter.config.extra = {}# Cloud-API-specific attributes- adapter._phone_number_id = overrides.pop("phone_number_id", "1234567890")+ adapter._phone_number_id = overrides.pop("phone_number_id", "7794189252778687")adapter._access_token = overrides.pop("access_token", "test-token")adapter._app_id = overrides.pop("app_id", "")adapter._app_secret = overrides.pop("app_secret", "")- adapter._waba_id = overrides.pop("waba_id", "")+ adapter._waba_id = overrides.pop("waba_id", "215589313241560883")adapter._verify_token = overrides.pop("verify_token", "")adapter._webhook_host = "127.0.0.1"adapter._webhook_port = 8090@@ -469,13 +469,13 @@ class TestWebhookDispatch:"object": "whatsapp_business_account","entry": [{- "id": "x",+ "id": "215589313241560883","changes": [{"field": "messages","value": {"messaging_product": "whatsapp",- "metadata": {"phone_number_id": "1"},+ "metadata": {"phone_number_id": "7794189252778687"},"contacts": [{"profile": {"name": "U"}, "wa_id": "1555"}],@@ -821,12 +821,12 @@ class TestInboundMediaDispatch:payload = {"object": "whatsapp_business_account","entry": [{- "id": "x",+ "id": "215589313241560883","changes": [{"field": "messages","value": {"messaging_product": "whatsapp",- "metadata": {"phone_number_id": "1"},+ "metadata": {"phone_number_id": "7794189252778687"},"contacts": [{"profile": {"name": "U"}, "wa_id": "1555"}],"messages": [{"from": "1555",diff --git a/tests/gateway/test_whatsapp_cloud_account_binding.py b/tests/gateway/test_whatsapp_cloud_account_binding.pynew file mode 100644index 00000000000..02310c00888--- /dev/null+++ b/tests/gateway/test_whatsapp_cloud_account_binding.py@@ -0,0 +1,155 @@+"""WhatsApp Cloud webhook account/phone binding regression tests.++All Meta identifiers and signatures are synthetic; no network is used.+"""++from __future__ import annotations++import asyncio+import hashlib+import hmac+import json+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import PlatformConfig+from gateway.platforms.whatsapp_cloud import WhatsAppCloudAdapter+++_SHARED_APP_SECRET = "a" * 32+_WABA_A = "100000000000001"+_PHONE_A = "200000000000001"+_WABA_B = "100000000000002"+_PHONE_B = "200000000000002"+_SENDER = "199900000000001"+++class _RequestContent:+ def __init__(self, body: bytes):+ self._body = body++ async def readexactly(self, size: int) -> bytes:+ if len(self._body) < size:+ raise asyncio.IncompleteReadError(self._body, size)+ return self._body[:size]+++def _request(body: bytes):+ request = MagicMock()+ request.content = _RequestContent(body)+ signature = hmac.new(_SHARED_APP_SECRET.encode(), body, hashlib.sha256).hexdigest()+ request.headers = {"X-Hub-Signature-256": f"sha256={signature}"}+ return request+++def _config(waba_id: str, phone_number_id: str) -> PlatformConfig:+ return PlatformConfig(+ enabled=True,+ extra={+ "waba_id": waba_id,+ "phone_number_id": phone_number_id,+ "access_token": "EAA" + "f" * 100,+ "app_secret": _SHARED_APP_SECRET,+ },+ )+++def _adapter(config: PlatformConfig) -> WhatsAppCloudAdapter:+ adapter = WhatsAppCloudAdapter(config)+ adapter.handle_message = AsyncMock()+ adapter._download_media_to_cache = AsyncMock(+ return_value=("/synthetic/inbound.jpg", "image/jpeg")+ )+ return adapter+++def _payload(waba_id: str, phone_number_id: str, *, media: bool) -> dict:+ message = {+ "from": _SENDER,+ "id": f"wamid.synthetic.{waba_id}.{phone_number_id}",+ "timestamp": "0",+ "type": "image" if media else "text",+ }+ if media:+ message["image"] = {+ "id": "synthetic-media-id",+ "mime_type": "image/jpeg",+ }+ else:+ message["text"] = {"body": "synthetic message"}+ return {+ "object": "whatsapp_business_account",+ "entry": [+ {+ "id": waba_id,+ "changes": [+ {+ "field": "messages",+ "value": {+ "messaging_product": "whatsapp",+ "metadata": {+ "display_phone_number": "+0 000 000 0000",+ "phone_number_id": phone_number_id,+ },+ "contacts": [+ {"profile": {"name": "Synthetic User"}, "wa_id": _SENDER}+ ],+ "messages": [message],+ },+ }+ ],+ }+ ],+ }+++ ("webhook_waba_id", "webhook_phone_number_id"),+ [+ (_WABA_B, _PHONE_A),+ (_WABA_A, _PHONE_B),+ (_WABA_B, _PHONE_B),+ ],+ ids=["foreign-waba", "foreign-phone", "foreign-waba-and-phone"],+)+async def test_signed_foreign_identity_is_dropped_before_media_or_dispatch(+ monkeypatch, webhook_waba_id, webhook_phone_number_id+):+ monkeypatch.setenv("WHATSAPP_CLOUD_ALLOW_ALL_USERS", "true")+ profile_a = _adapter(_config(_WABA_A, _PHONE_A))+ profile_b = _adapter(_config(_WABA_B, _PHONE_B))+ body = json.dumps(_payload(webhook_waba_id, webhook_phone_number_id, media=True)).encode()+ request = _request(body)++ assert profile_a._verify_signature(body, request.headers["X-Hub-Signature-256"])+ assert profile_b._verify_signature(body, request.headers["X-Hub-Signature-256"])++ response = await profile_a._handle_webhook(request)++ assert response.status == 200+ profile_a._download_media_to_cache.assert_not_awaited()+ profile_a.handle_message.assert_not_awaited()+ assert profile_a._accepted_count == 0+++async def test_identity_change_requires_explicit_adapter_reconfiguration(monkeypatch):+ monkeypatch.setenv("WHATSAPP_CLOUD_ALLOW_ALL_USERS", "true")+ original_config = _config(_WABA_A, _PHONE_A)+ original = _adapter(original_config)+ original_config.extra.update(waba_id=_WABA_B, phone_number_id=_PHONE_B)+ body = json.dumps(_payload(_WABA_B, _PHONE_B, media=False)).encode()++ response = await original._handle_webhook(_request(body))++ assert response.status == 200+ original.handle_message.assert_not_awaited()++ reconfigured = _adapter(_config(_WABA_B, _PHONE_B))+ response = await reconfigured._handle_webhook(_request(body))++ assert response.status == 200+ reconfigured.handle_message.assert_awaited_once()+ assert reconfigured.handle_message.await_args.args[0].text == "synthetic message"diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex 103d06b3001..0eb4fe936b9 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -402,7 +402,7 @@ These are set automatically by the Docker terminal backend when `proxy.enabled:| `WHATSAPP_CLOUD_ALLOWED_USERS` | Comma-separated `wa_id`s (phone numbers with country code, no `+`) allowed to message the bot || `WHATSAPP_CLOUD_ALLOW_ALL_USERS` | Allow all WhatsApp Cloud senders without an allowlist (`true`/`false`) || `WHATSAPP_CLOUD_APP_ID` | Optional Meta App ID (for future analytics integration) |-| `WHATSAPP_CLOUD_WABA_ID` | Optional WhatsApp Business Account ID (for future analytics integration) |+| `WHATSAPP_CLOUD_WABA_ID` | Optional WhatsApp Business Account ID; when set, inbound webhooks must match it || `WHATSAPP_CLOUD_WEBHOOK_HOST` | Interface the inbound webhook server binds to (default `0.0.0.0`) || `WHATSAPP_CLOUD_WEBHOOK_PORT` | Port the inbound webhook server binds to (default `8090`) || `WHATSAPP_CLOUD_WEBHOOK_PATH` | URL path Meta posts inbound messages to (default `/whatsapp/webhook`) |diff --git a/website/docs/user-guide/messaging/whatsapp-cloud.md b/website/docs/user-guide/messaging/whatsapp-cloud.mdindex 4e5f4e5fe81..51aa19f9188 100644--- a/website/docs/user-guide/messaging/whatsapp-cloud.md+++ b/website/docs/user-guide/messaging/whatsapp-cloud.md@@ -65,7 +65,7 @@ You'll need these values from the dashboard — the wizard prompts for them in t| **Access Token** | App Dashboard → WhatsApp → API Setup → "Generate access token" | Starts with `EAA`, 100+ chars | Temp tokens last 24h — see "Permanent token" below for production. || **App Secret** | App Dashboard → Settings → Basic → click "Show" next to App secret | 32-character lowercase hex | Used to verify incoming webhook signatures. Without it, inbound delivery is refused with 503. || **App ID** (optional) | App Dashboard → Settings → Basic | Numeric, 15-16 digits | Not required for messaging, useful for analytics. |-| **WABA ID** (optional) | App Dashboard → WhatsApp → API Setup → near the top | Numeric, 15+ digits | Not required for messaging, useful for analytics. |+| **WABA ID** (optional) | App Dashboard → WhatsApp → API Setup → near the top | Numeric, 15+ digits | When set, inbound webhooks must match this business account. |---@@ -228,7 +228,7 @@ All settings live in `~/.hermes/.env`. Required values are in **bold**.| **`WHATSAPP_CLOUD_ALLOWED_USERS`** | — | Comma-separated wa_ids allowed to message the bot. || `WHATSAPP_CLOUD_ALLOW_ALL_USERS` | `false` | Set to `true` to bypass the allowlist. || `WHATSAPP_CLOUD_APP_ID` | — | Optional, for future analytics integration. |-| `WHATSAPP_CLOUD_WABA_ID` | — | Optional, for future analytics integration. |+| `WHATSAPP_CLOUD_WABA_ID` | — | Optional; when set, inbound webhooks must match this business account. || `WHATSAPP_CLOUD_WEBHOOK_HOST` | unset (dual-stack: all interfaces, IPv4+IPv6) | Interface the webhook server binds to. || `WHATSAPP_CLOUD_WEBHOOK_PORT` | `8090` | Port the webhook server binds to. Must match the port your tunnel forwards. || `WHATSAPP_CLOUD_WEBHOOK_PATH` | `/whatsapp/webhook` | URL path Meta posts to. |