The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(buzz): gate authenticated inbound media on explicit authorization
Mathias Gorfaaad05433026
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 3bae3ab645f..8b37cd73ca7 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3907,11 +3907,26 @@ class BasePlatformAdapter(ABC):registered via :meth:`set_authorization_check`. Returns ``None``when no check is registered (caller should treat as "trust unknown"and preserve legacy behaviour).++ Only the literal booleans are propagated. A callback that returns+ anything else is treated as "unknown" rather than coerced with+ ``bool()``: callers that gate a credentialed side effect on an+ explicit ``is True`` must not have a truthy non-boolean (a status+ string, a sentinel object) silently promoted to an authorization."""if not user_id or self._authorization_check is None:return Nonetry:- return bool(self._authorization_check(user_id, chat_type, chat_id))+ result = self._authorization_check(user_id, chat_type, chat_id)+ if result is True:+ return True+ if result is False:+ return False+ logger.warning(+ "[%s] Authorization check returned %s for user %s; treating as unknown",+ self.name, type(result).__name__, user_id,+ )+ return Noneexcept Exception:logger.warning("[%s] Authorization check raised for user %s; treating as unknown",diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.pyindex cdf14ff3c2e..4d37a3419b1 100644--- a/plugins/platforms/buzz/adapter.py+++ b/plugins/platforms/buzz/adapter.py@@ -2361,17 +2361,38 @@ class BuzzAdapter(BasePlatformAdapter):return Nonereturn str(entry[0] or ""), str(entry[1] or "")async def _localize_inbound_media(- self, text: str, message_id: str+ self,+ text: str,+ message_id: str,+ *,+ user_id: str = "",+ chat_type: Optional[str] = None,+ chat_id: Optional[str] = None,) -> Tuple[str, List[str], List[str], MessageType]:"""Authenticate and cache same-relay media references in *text*.Each object is independent: one failed download is logged and skippedwithout discarding the caption or any other successfully cached files.++ Downloading spends this agent's Buzz credentials on a URL chosen by+ the sender, so it runs only when the gateway's authorization callback+ returns an explicit ``True``. The adapter's own ``allowed_users``+ list is a pre-filter, not a substitute: a missing, failed, or+ negative gateway decision leaves the text untouched and no+ credentialed request is made."""urls, replacements = _find_relay_media_refs(text, self.relay_url)if not urls:return text, [], [], MessageType.TEXT+ if self._is_sender_authorized(user_id, chat_type, chat_id) is not True:+ logger.warning(+ "Buzz: not localizing %d media reference(s) in message %s — "+ "sender %s… is not explicitly authorized",+ len(urls), message_id[:12], (user_id or "?")[:8],+ )+ return text, [], [], MessageType.TEXT+cleaned_text = _replace_media_refs(text, replacements)media_urls: List[str] = []media_types: List[str] = []@@ -2475,7 +2496,11 @@ class BuzzAdapter(BasePlatformAdapter):returntext, media_urls, media_types, message_type = await self._localize_inbound_media(- text, message_id+ text,+ message_id,+ user_id=user_id,+ chat_type=chat_type,+ chat_id=chat_id,)source = self.build_source(diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.pyindex 554ff3c3d73..a1d2868ccba 100644--- a/tests/gateway/test_buzz_adapter.py+++ b/tests/gateway/test_buzz_adapter.py@@ -1599,6 +1599,11 @@ class TestInboundMediaLocalisation:adapter._message_handler = AsyncMock()adapter.send_reaction = AsyncMock(return_value=True)adapter._run_cli = cli+ # Localisation spends the agent's Buzz credentials, so it is gated on+ # an explicit gateway authorization. The gateway registers this check+ # on every adapter it constructs; tests are authorized by default and+ # override the callback where the gate itself is under test.+ adapter.set_authorization_check(lambda *_args: True)return captured, cli_calls@pytest.mark.asyncio@@ -1809,6 +1814,9 @@ class TestInboundMediaLocalisation:adapter._message_handler = AsyncMock()adapter.send_reaction = AsyncMock(return_value=True)adapter._run_cli = cli+ # As the gateway does for every adapter it constructs; the gate itself+ # is covered by TestInboundMediaAuthorizationGate.+ adapter.set_authorization_check(lambda *_args: True)await adapter._handle_event(DM_CHANNEL,@@ -1851,6 +1859,113 @@ class TestInboundMediaLocalisation:assert calls == []+class TestInboundMediaAuthorizationGate:+ """Authenticated retrieval must never run for an unauthorized sender.++ ``buzz media get`` signs the request with this agent's own key, so a+ relay object named by an unauthorized sender must not be fetched or+ cached. Every non-``True`` outcome — denial, no registered check, a+ raising check, or a truthy non-boolean — must fail closed and leave the+ message text exactly as it arrived.+ """++ @staticmethod+ def _media_text():+ return f"look at this "++ async def _dispatch_with_check(self, adapter, monkeypatch, tmp_path, check):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))+ captured, cli_calls = TestInboundMediaLocalisation._capture_dispatch(adapter)+ adapter.set_authorization_check(check)+ text = self._media_text()++ await adapter._dispatch_message(+ text=text,+ chat_id=CHANNEL,+ chat_type="group",+ user_id=OTHER_PUBKEY,+ user_name="Joel",+ message_id="gated-media-event",+ created_at=1007,+ )+ return captured, cli_calls, text++ @pytest.mark.asyncio+ async def test_denied_sender_media_is_not_downloaded(self, monkeypatch, tmp_path):+ adapter = _make_adapter()+ captured, cli_calls, text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, lambda *_args: False+ )++ assert cli_calls == []+ assert captured[0].text == text+ assert captured[0].message_type == MessageType.TEXT+ assert captured[0].media_urls == []++ @pytest.mark.asyncio+ async def test_missing_authorization_check_blocks_download(self, monkeypatch, tmp_path):+ adapter = _make_adapter()+ captured, cli_calls, text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, None+ )++ assert cli_calls == []+ assert captured[0].text == text+ assert captured[0].media_urls == []++ @pytest.mark.asyncio+ async def test_raising_authorization_check_blocks_download(self, monkeypatch, tmp_path):+ def boom(*_args):+ raise RuntimeError("auth backend down")++ adapter = _make_adapter()+ captured, cli_calls, text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, boom+ )++ assert cli_calls == []+ assert captured[0].text == text+ assert captured[0].media_urls == []++ @pytest.mark.asyncio+ async def test_truthy_non_boolean_is_not_an_authorization(self, monkeypatch, tmp_path):+ """A non-boolean result must not be coerced into a credentialed fetch."""+ adapter = _make_adapter()+ captured, cli_calls, text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, lambda *_args: "allowed"+ )++ assert cli_calls == []+ assert captured[0].text == text+ assert captured[0].media_urls == []++ @pytest.mark.asyncio+ async def test_adapter_allowlist_does_not_override_gateway_denial(+ self, monkeypatch, tmp_path+ ):+ """``allowed_users`` is a pre-filter, not a second source of truth."""+ adapter = _make_adapter({"allowed_users": [OTHER_PUBKEY]})+ captured, cli_calls, _text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, lambda *_args: False+ )++ assert OTHER_PUBKEY in adapter._allowed_pubkeys+ assert cli_calls == []+ assert captured[0].media_urls == []++ @pytest.mark.asyncio+ async def test_authorized_sender_still_downloads(self, monkeypatch, tmp_path):+ """The gate must not break the happy path it protects."""+ adapter = _make_adapter()+ captured, cli_calls, _text = await self._dispatch_with_check(+ adapter, monkeypatch, tmp_path, lambda *_args: True+ )++ assert len(cli_calls) == 1+ assert captured[0].message_type == MessageType.PHOTO+ assert len(captured[0].media_urls) == 1++# ── Lifecycle ─────────────────────────────────────────────────────────────diff --git a/tests/gateway/test_platform_base.py b/tests/gateway/test_platform_base.pyindex 30ef0c837f4..4d12ec90dac 100644--- a/tests/gateway/test_platform_base.py+++ b/tests/gateway/test_platform_base.py@@ -943,6 +943,72 @@ class TestShouldSendMediaAsAudio:# ---------------------------------------------------------------------------+class TestIsSenderAuthorized:+ """``_is_sender_authorized`` is a tri-state: True / False / unknown.++ Callers gate credentialed side effects on an explicit ``is True``, so a+ truthy non-boolean must resolve to unknown rather than being coerced+ into an authorization by ``bool()``.+ """++ def _adapter(self):+ class StubAdapter(BasePlatformAdapter):+ async def connect(self, *, is_reconnect: bool = False):+ return True++ async def disconnect(self):+ pass++ async def send(self, *a, **kw):+ pass++ async def get_chat_info(self, *a):+ return {}++ from gateway.config import Platform, PlatformConfig++ return StubAdapter(config=PlatformConfig(enabled=True, token="test"),+ platform=Platform.TELEGRAM)++ def test_no_check_registered_is_unknown(self):+ assert self._adapter()._is_sender_authorized("user") is None++ def test_empty_user_id_is_unknown(self):+ adapter = self._adapter()+ adapter.set_authorization_check(lambda *_a: True)+ assert adapter._is_sender_authorized("") is None++ def test_true_and_false_propagate(self):+ adapter = self._adapter()+ adapter.set_authorization_check(lambda *_a: True)+ assert adapter._is_sender_authorized("user") is True+ adapter.set_authorization_check(lambda *_a: False)+ assert adapter._is_sender_authorized("user") is False++ @pytest.mark.parametrize("result", ["allowed", 1, object(), [1]])+ def test_truthy_non_boolean_is_unknown(self, result):+ adapter = self._adapter()+ adapter.set_authorization_check(lambda *_a: result)+ assert adapter._is_sender_authorized("user") is None++ def test_raising_check_is_unknown(self):+ def boom(*_a):+ raise RuntimeError("auth backend down")++ adapter = self._adapter()+ adapter.set_authorization_check(boom)+ assert adapter._is_sender_authorized("user") is None++ def test_check_receives_chat_context(self):+ seen = []+ adapter = self._adapter()+ adapter.set_authorization_check(+ lambda user_id, chat_type, chat_id: seen.append((user_id, chat_type, chat_id)) or True+ )+ adapter._is_sender_authorized("user", "group", "chan")+ assert seen == [("user", "group", "chan")]++class TestTruncateMessage:def _adapter(self):"""Create a minimal adapter instance for testing static/instance methods."""diff --git a/website/docs/user-guide/messaging/buzz.md b/website/docs/user-guide/messaging/buzz.mdindex 1ee240ed80c..898a92a5d72 100644--- a/website/docs/user-guide/messaging/buzz.md+++ b/website/docs/user-guide/messaging/buzz.md@@ -4,6 +4,8 @@ The Buzz adapter connects Hermes to a [Buzz](https://github.com/block/buzz) commBuzz renders markdown, so agent replies keep their formatting. Images are delivered as uploads (local files) or links (URLs). Replies can thread onto an existing message via its event id. When progress or status messages are enabled, they inherit the triggering Buzz event as their reply anchor instead of appearing as unrelated top-level channel posts.+Files sent **to** the agent are fetched back off the relay with the agent's authenticated identity and cached locally, so tools receive a real file path rather than a `/media/…` URL that anonymous requests cannot read. Images, audio, video, and documents (PDFs and the like) are all handled.+Inbound messages arrive over a persistent NIP-42-authenticated Nostr WebSocket subscription by default (near-instant delivery), with automatic fallback to CLI polling when the WebSocket can't be established. Outbound messages always go through the `buzz` CLI. Control it with `transport` / `BUZZ_TRANSPORT`: `auto` (default), `websocket` (require WS, fail otherwise), or `poll`. If your relay membership uses NIP-OA owner attestation, set `BUZZ_AUTH_TAG` to the four-string auth tag JSON.> Run `hermes gateway setup` and pick **Buzz** for a guided walk-through.@@ -122,6 +124,8 @@ The opt-out applies to **all** send paths — final answers, streamed updates, iBy default the allow-list is empty, which means every community member who mentions the agent gets a response only if `BUZZ_ALLOW_ALL_USERS=true`; otherwise restrict access by listing npubs or hex pubkeys in `BUZZ_ALLOWED_USERS` (or `allowed_users` in config.yaml). Community membership itself is enforced by the relay — only members can post.+The allow-list also gates **inbound attachments**: relay media is fetched with the agent's own Buzz credentials, so a download only happens for a sender the gateway explicitly authorizes. A denied, missing, or failed authorization leaves the message text untouched and makes no credentialed request.+Cron jobs and notifications (`deliver=buzz`) are delivered to the **home channel** — `BUZZ_HOME_CHANNEL` if set, otherwise the first watched channel — and work even when cron runs outside the gateway process.## Run the gateway