From 1d4000560dfff1acb83f5c5ca8ef3ab1f092bd14 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Sat, 30 May 2026 15:28:27 +0800 Subject: [PATCH] fix(matrix): reject boolean media sizes --- nanobot/channels/matrix.py | 2 +- tests/channels/test_matrix_channel.py | 28 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/nanobot/channels/matrix.py b/nanobot/channels/matrix.py index 9bb665684..d2a1d95d3 100644 --- a/nanobot/channels/matrix.py +++ b/nanobot/channels/matrix.py @@ -749,7 +749,7 @@ class MatrixChannel(BaseChannel): def _event_declared_size_bytes(self, event: MatrixMediaEvent) -> int | None: info = self._event_source_content(event).get("info") size = info.get("size") if isinstance(info, dict) else None - return size if isinstance(size, int) and size >= 0 else None + return size if type(size) is int and size >= 0 else None def _event_mime(self, event: MatrixMediaEvent) -> str | None: info = self._event_source_content(event).get("info") diff --git a/tests/channels/test_matrix_channel.py b/tests/channels/test_matrix_channel.py index 7eb9f73a1..2bf6a28cd 100644 --- a/tests/channels/test_matrix_channel.py +++ b/tests/channels/test_matrix_channel.py @@ -1828,6 +1828,34 @@ async def test_fetch_media_rejects_missing_declared_size(monkeypatch, tmp_path) assert marker == "[attachment: payload.bin - too large]" +@pytest.mark.asyncio +async def test_fetch_media_rejects_bool_declared_size(monkeypatch, tmp_path) -> None: + channel = MatrixChannel(_make_config(max_media_bytes=8), MessageBus()) + client = _FakeAsyncClient("https://matrix.org", "", "", None) + channel.client = client + monkeypatch.setattr("nanobot.channels.matrix.get_media_dir", lambda _name: tmp_path) + + async def _download_should_not_run(*_args, **_kwargs): + raise AssertionError("bool size should be rejected before fetching bytes") + + monkeypatch.setattr(channel, "_download_media_bytes", _download_should_not_run) + event = SimpleNamespace( + sender="@alice:matrix.org", + event_id="$event1", + body="payload.bin", + url="mxc://example.org/media", + source={"content": {"msgtype": "m.file", "info": {"size": True}}}, + ) + + attachment, marker = await channel._fetch_media_attachment( + SimpleNamespace(room_id="!room:matrix.org"), + event, + ) + + assert attachment is None + assert marker == "[attachment: payload.bin - too large]" + + @pytest.mark.asyncio async def test_fetch_media_rejects_declared_oversized_before_download(monkeypatch, tmp_path) -> None: channel = MatrixChannel(_make_config(max_media_bytes=8), MessageBus())