Skip to content

The agent that grows with you

fix(buzz): gate inbound attachment side effects

EmpireOperatingd15cbbcbf317
diff --git a/plugins/platforms/buzz/adapter.py b/plugins/platforms/buzz/adapter.py
index eb4be8f3f88..15b5b0231a2 100644
--- a/plugins/platforms/buzz/adapter.py
+++ b/plugins/platforms/buzz/adapter.py
@@ -2054,18 +2054,20 @@ class BuzzAdapter(BasePlatformAdapter):
self._save_cursors()
@staticmethod
- def _imeta_attachments(event: dict) -> List[dict]:
- """Return bounded, structurally valid NIP-94 attachment metadata."""
+ def _parse_imeta_attachments(event: dict) -> Tuple[List[dict], int]:
+ """Return accepted NIP-94 metadata and the rejected ``imeta`` count."""
tags = event.get("tags")
if not isinstance(tags, list):
- return []
+ return [], 0
attachments: List[dict] = []
+ rejected = 0
total_declared_bytes = 0
for tag in tags:
- if len(attachments) >= _MAX_INBOUND_ATTACHMENTS:
- break
if not isinstance(tag, (list, tuple)) or not tag or tag[0] != "imeta":
continue
+ if len(attachments) >= _MAX_INBOUND_ATTACHMENTS:
+ rejected += 1
+ continue
fields: Dict[str, str] = {}
for raw_field in tag[1:]:
if not isinstance(raw_field, str):
@@ -2079,15 +2081,13 @@ class BuzzAdapter(BasePlatformAdapter):
mime_type = fields.get("m", "")
try:
size = int(fields.get("size", ""))
- except (TypeError, ValueError):
- continue
- try:
parsed = urlsplit(url)
parsed_hostname = parsed.hostname
# Access validates malformed/non-numeric ports even though exact
# origin authorization occurs immediately before downloading.
parsed.port
- except ValueError:
+ except (TypeError, ValueError):
+ rejected += 1
continue
if (
parsed.scheme != "https"
@@ -2099,6 +2099,7 @@ class BuzzAdapter(BasePlatformAdapter):
or not 0 < size <= _MAX_INBOUND_ATTACHMENT_BYTES
or total_declared_bytes + size > _MAX_INBOUND_ATTACHMENT_BYTES
):
+ rejected += 1
continue
total_declared_bytes += size
attachments.append(
@@ -2110,8 +2111,20 @@ class BuzzAdapter(BasePlatformAdapter):
"mime_type": mime_type[:255],
}
)
+ return attachments, rejected
+
+ @staticmethod
+ def _imeta_attachments(event: dict) -> List[dict]:
+ """Return bounded, structurally valid NIP-94 attachment metadata."""
+ attachments, _rejected = BuzzAdapter._parse_imeta_attachments(event)
return attachments
+ @staticmethod
+ def _attachment_rejection_note(rejected: int) -> str:
+ """Return a fixed-width diagnostic for malformed or excess metadata."""
+ shown = str(rejected) if rejected <= 999 else "999+"
+ return f"[{shown} Buzz attachment(s) rejected as malformed or over limits.]"
+
async def _download_attachment(self, metadata: dict) -> Optional[CachedMedia]:
"""Download, integrity-check, and cache one authorized Buzz attachment."""
url = metadata["url"]
@@ -2212,11 +2225,12 @@ class BuzzAdapter(BasePlatformAdapter):
return
pubkey = str(event.get("pubkey") or "").lower()
content = event.get("content")
- attachment_metadata = self._imeta_attachments(event)
+ attachment_metadata, rejected_attachments = self._parse_imeta_attachments(event)
+ has_imeta = bool(attachment_metadata or rejected_attachments)
if (
not pubkey
or not isinstance(content, str)
- or (not content.strip() and not attachment_metadata)
+ or (not content.strip() and not has_imeta)
):
return
@@ -2285,10 +2299,28 @@ class BuzzAdapter(BasePlatformAdapter):
# Remember where this message sits in the thread graph so our reply
# can join the SAME thread rather than nesting a new one under it.
self._record_thread_root(event_id, event)
- # Network and cache access deliberately happen only after self-echo,
- # addressing, and sender allow-list authorization have all passed.
- attachments = await self._cache_inbound_attachments(attachment_metadata)
- if attachment_metadata and len(attachments) < len(attachment_metadata):
+ # Attachment fetch/cache is a security-sensitive side effect. Only the
+ # gateway's authoritative callback can permit it, and only an explicit
+ # True is permission: false, absent, or failed checks all fail closed.
+ # The message still dispatches so GatewayRunner can apply denial/pairing.
+ chat_type = "dm" if is_dm else "group"
+ attachment_fetch_allowed = bool(attachment_metadata) and (
+ self._is_sender_authorized(pubkey, chat_type, channel_id) is True
+ )
+ attachments = (
+ await self._cache_inbound_attachments(attachment_metadata)
+ if attachment_fetch_allowed
+ else []
+ )
+ if rejected_attachments:
+ dispatch_text = (
+ f"{dispatch_text}\n"
+ f"{self._attachment_rejection_note(rejected_attachments)}"
+ ).strip()
+ if (
+ attachment_fetch_allowed
+ and len(attachments) < len(attachment_metadata)
+ ):
failed = len(attachment_metadata) - len(attachments)
dispatch_text = (
f"{dispatch_text}\n"
@@ -2313,7 +2345,7 @@ class BuzzAdapter(BasePlatformAdapter):
await self._dispatch_message(
text=dispatch_text,
chat_id=channel_id,
- chat_type="dm" if is_dm else "group",
+ chat_type=chat_type,
user_id=pubkey,
user_name=await self._resolve_user_name(pubkey),
message_id=event_id,
diff --git a/tests/gateway/test_buzz_adapter.py b/tests/gateway/test_buzz_adapter.py
index 27c7d869891..59e34b57f3d 100644
--- a/tests/gateway/test_buzz_adapter.py
+++ b/tests/gateway/test_buzz_adapter.py
@@ -88,6 +88,9 @@ def _make_adapter(extra=None):
adapter._self_npub = SELF_NPUB
adapter._display_name = "Chip"
adapter._private_key = "nsec1test"
+ # GatewayRunner installs this callback before intake starts. Attachment
+ # tests are authorized by default and override the callback at the boundary.
+ adapter.set_authorization_check(lambda *_args: True)
return adapter
@@ -857,6 +860,9 @@ class TestInboundAttachments:
@pytest.mark.asyncio
async def test_unaddressed_channel_attachment_is_not_downloaded(self):
adapter = _make_adapter()
+ authorization_check = MagicMock(return_value=True)
+ adapter.set_authorization_check(authorization_check)
+ adapter._cache_inbound_attachments = AsyncMock()
adapter._download_attachment = AsyncMock()
adapter._channel_state[CHANNEL] = {
"chat_type": "group",
@@ -875,6 +881,8 @@ class TestInboundAttachments:
await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+ authorization_check.assert_not_called()
+ adapter._cache_inbound_attachments.assert_not_awaited()
adapter._download_attachment.assert_not_awaited()
@pytest.mark.asyncio
@@ -1010,6 +1018,70 @@ class TestInboundAttachments:
assert dispatched[-1]["media_urls"] == [attachment.path]
assert dispatched[-1]["message_type"] is MessageType.DOCUMENT
+ @pytest.mark.asyncio
+ async def test_malformed_attachment_only_dm_dispatches_once_with_bounded_note(self):
+ adapter = _make_adapter()
+ adapter._download_attachment = AsyncMock()
+ adapter._user_names[OTHER_PUBKEY] = "Other"
+ adapter._channel_state[DM_CHANNEL] = {
+ "chat_type": "dm",
+ "last_ts": 0,
+ "seen": {},
+ }
+ adapter._dispatch_message = AsyncMock()
+ event = _event("malformed-attachment-only", content="")
+ event["tags"].append(["imeta", "url definitely-not-a-url"])
+
+ await adapter._handle_event(DM_CHANNEL, adapter._channel_state[DM_CHANNEL], event)
+ await adapter._handle_event(DM_CHANNEL, adapter._channel_state[DM_CHANNEL], event)
+
+ adapter._download_attachment.assert_not_awaited()
+ adapter._dispatch_message.assert_awaited_once()
+ call = adapter._dispatch_message.await_args
+ assert call is not None
+ dispatched = call.kwargs
+ assert "1 Buzz attachment(s) rejected" in dispatched["text"]
+ assert len(dispatched["text"]) <= 80
+ assert dispatched["media_urls"] == []
+
+ @pytest.mark.asyncio
+ async def test_excess_imeta_is_reported_while_accepted_files_remain_attached(self):
+ adapter = _make_adapter()
+ adapter._user_names[OTHER_PUBKEY] = "Other"
+ adapter._channel_state[CHANNEL] = {
+ "chat_type": "group",
+ "last_ts": 0,
+ "seen": {},
+ }
+ adapter._download_attachment = AsyncMock(
+ side_effect=lambda metadata: CachedMedia(
+ f"/cache/{metadata['filename']}",
+ metadata["mime_type"],
+ "document",
+ metadata["filename"],
+ )
+ )
+ adapter._dispatch_message = AsyncMock()
+ event = _event("excess-imeta", content="@Chip inspect")
+ for index in range(5):
+ event["tags"].append([
+ "imeta",
+ f"url https://test.relay/media/{index}.bin",
+ "m application/octet-stream",
+ "x " + format(index + 1, "064x"),
+ "size 1",
+ f"filename {index}.bin",
+ ])
+
+ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+
+ assert adapter._download_attachment.await_count == 4
+ call = adapter._dispatch_message.await_args
+ assert call is not None
+ dispatched = call.kwargs
+ assert "1 Buzz attachment(s) rejected" in dispatched["text"]
+ assert len(dispatched["media_urls"]) == 4
+
def test_imeta_bounds_filename_to_filesystem_safe_utf8_length(self):
event = _event("long-name", content="@Chip file")
event["tags"].append([
@@ -1209,10 +1281,41 @@ class TestInboundAttachments:
assert len(attachments) == 4
assert all("@" not in item["url"] and "#" not in item["url"] for item in attachments)
+ @pytest.mark.asyncio
+ async def test_self_attachment_stops_before_authorization_or_cache(self):
+ adapter = _make_adapter()
+ authorization_check = MagicMock(return_value=True)
+ adapter.set_authorization_check(authorization_check)
+ adapter._cache_inbound_attachments = AsyncMock()
+ adapter._dispatch_message = AsyncMock()
+ adapter._channel_state[CHANNEL] = {
+ "chat_type": "group",
+ "last_ts": 0,
+ "seen": {},
+ }
+ event = _event("self-attachment", pubkey=SELF_PUBKEY, content="@Chip inspect")
+ event["tags"].append([
+ "imeta",
+ "url https://test.relay/media/file.bin",
+ "m application/octet-stream",
+ "x " + "a" * 64,
+ "size 1",
+ "filename file.bin",
+ ])
+
+ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+
+ authorization_check.assert_not_called()
+ adapter._cache_inbound_attachments.assert_not_awaited()
+ adapter._dispatch_message.assert_not_awaited()
+
@pytest.mark.asyncio
async def test_unauthorized_sender_attachment_is_not_downloaded(self):
adapter = _make_adapter()
adapter._allowed_pubkeys = {"f" * 64}
+ authorization_check = MagicMock(return_value=True)
+ adapter.set_authorization_check(authorization_check)
+ adapter._cache_inbound_attachments = AsyncMock()
adapter._download_attachment = AsyncMock()
adapter._channel_state[CHANNEL] = {
"chat_type": "group",
@@ -1231,8 +1334,130 @@ class TestInboundAttachments:
await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+ authorization_check.assert_not_called()
+ adapter._cache_inbound_attachments.assert_not_awaited()
adapter._download_attachment.assert_not_awaited()
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("authorization", [False, None, "raise"])
+ async def test_non_true_gateway_authority_never_caches_even_for_locally_allowed_sender(
+ self,
+ authorization,
+ ):
+ adapter = _make_adapter()
+ adapter._allowed_pubkeys = {OTHER_PUBKEY}
+ if authorization is None:
+ adapter.set_authorization_check(None)
+ elif authorization == "raise":
+ def raise_unknown(*_args):
+ raise RuntimeError("authorization backend unavailable")
+
+ adapter.set_authorization_check(raise_unknown)
+ else:
+ adapter.set_authorization_check(lambda *_args: False)
+ adapter._cache_inbound_attachments = AsyncMock()
+ adapter._dispatch_message = AsyncMock()
+ adapter._channel_state[CHANNEL] = {
+ "chat_type": "group",
+ "last_ts": 0,
+ "seen": {},
+ }
+ event = _event(f"gateway-{authorization}-attachment", content="@Chip inspect")
+ event["tags"].append([
+ "imeta",
+ "url https://test.relay/media/file.bin",
+ "m application/octet-stream",
+ "x " + "a" * 64,
+ "size 1",
+ "filename file.bin",
+ ])
+
+ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+
+ adapter._cache_inbound_attachments.assert_not_awaited()
+ adapter._dispatch_message.assert_awaited_once()
+ call = adapter._dispatch_message.await_args
+ assert call is not None
+ assert call.kwargs["media_urls"] == []
+
+ @pytest.mark.asyncio
+ async def test_explicit_true_gateway_authority_caches_attachment(self):
+ adapter = _make_adapter()
+ authorization_check = MagicMock(return_value=True)
+ adapter.set_authorization_check(authorization_check)
+ cached = CachedMedia(
+ "/cache/authorized.bin",
+ "application/octet-stream",
+ "document",
+ "authorized.bin",
+ )
+ adapter._cache_inbound_attachments = AsyncMock(return_value=[cached])
+ adapter._dispatch_message = AsyncMock()
+ adapter._channel_state[CHANNEL] = {
+ "chat_type": "group",
+ "last_ts": 0,
+ "seen": {},
+ }
+ event = _event("gateway-authorized-attachment", content="@Chip inspect")
+ event["tags"].append([
+ "imeta",
+ "url https://test.relay/media/file.bin",
+ "m application/octet-stream",
+ "x " + "a" * 64,
+ "size 1",
+ "filename file.bin",
+ ])
+
+ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+
+ authorization_check.assert_called_once_with(OTHER_PUBKEY, "group", CHANNEL)
+ adapter._cache_inbound_attachments.assert_awaited_once()
+ call = adapter._dispatch_message.await_args
+ assert call is not None
+ assert call.kwargs["media_urls"] == [cached.path]
+
+ @pytest.mark.asyncio
+ async def test_real_gateway_auth_callback_defaults_to_no_attachment_side_effects(
+ self,
+ monkeypatch,
+ ):
+ from gateway.config import GatewayConfig
+ from gateway.run import GatewayRunner
+
+ monkeypatch.delenv("GATEWAY_ALLOWED_USERS", raising=False)
+ monkeypatch.delenv("GATEWAY_ALLOW_ALL_USERS", raising=False)
+ runner = object.__new__(GatewayRunner)
+ runner.config = GatewayConfig()
+ runner.adapters = {}
+ runner.pairing_store = MagicMock()
+ runner.pairing_store.is_approved.return_value = False
+
+ adapter = _make_adapter()
+ adapter._allowed_pubkeys = {OTHER_PUBKEY}
+ adapter.set_authorization_check(runner._make_adapter_auth_check(adapter.platform))
+ adapter._cache_inbound_attachments = AsyncMock()
+ adapter._dispatch_message = AsyncMock()
+ adapter._channel_state[CHANNEL] = {
+ "chat_type": "group",
+ "last_ts": 0,
+ "seen": {},
+ }
+ event = _event("gateway-default-denied-attachment", content="@Chip inspect")
+ event["tags"].append([
+ "imeta",
+ "url https://test.relay/media/file.bin",
+ "m application/octet-stream",
+ "x " + "a" * 64,
+ "size 1",
+ "filename file.bin",
+ ])
+
+ await adapter._handle_event(CHANNEL, adapter._channel_state[CHANNEL], event)
+
+ runner.pairing_store.is_approved.assert_called_once_with("buzz", OTHER_PUBKEY)
+ adapter._cache_inbound_attachments.assert_not_awaited()
+ adapter._dispatch_message.assert_awaited_once()
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("kind", "mime_type", "expected_type"),