diff --git a/nanobot/channels/dingtalk/runtime.py b/nanobot/channels/dingtalk/runtime.py index 982398669..257eb1008 100644 --- a/nanobot/channels/dingtalk/runtime.py +++ b/nanobot/channels/dingtalk/runtime.py @@ -489,89 +489,46 @@ class DingTalkChannel(BaseChannel): return None, None try: - # Prefer streaming with a running byte cap so large responses are not - # materialized before the limit is enforced. Test fakes may only - # implement get(), so keep a small compatibility fallback below. - stream = getattr(self._http, "stream", None) - if stream is not None: - current_url = media_ref - for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1): - async with stream("GET", current_url, follow_redirects=False) as resp: - final_ok, final_err = validate_resolved_url(str(resp.url)) - if not final_ok: - self.logger.warning( - "remote media redirect blocked ref={} final={} reason={}", - media_ref, - resp.url, - final_err, - ) - return None, None - if 300 <= resp.status_code < 400: - next_url = self._next_remote_media_url( - str(resp.url), resp.headers.get("location") - ) - if not next_url: - return None, None - current_url = next_url - continue - if resp.status_code >= 400: - self.logger.warning( - "media download failed status={} ref={}", - resp.status_code, - current_url, - ) - return None, None - chunks: list[bytes] = [] - total = 0 - async for chunk in resp.aiter_bytes(): - total += len(chunk) - if total > DINGTALK_MAX_REMOTE_MEDIA_BYTES: - self.logger.warning( - "media download too large ref={} bytes>{}", - current_url, - DINGTALK_MAX_REMOTE_MEDIA_BYTES, - ) - return None, None - chunks.append(chunk) - return b"".join(chunks), (resp.headers.get("content-type") or "") - self.logger.warning("media download exceeded redirect limit ref={}", media_ref) - return None, None - current_url = media_ref for _ in range(DINGTALK_MAX_REMOTE_MEDIA_REDIRECTS + 1): - resp = await self._http.get(current_url, follow_redirects=False) - final_ok, final_err = validate_resolved_url(str(getattr(resp, "url", current_url))) - if not final_ok: - self.logger.warning( - "remote media redirect blocked ref={} final={} reason={}", - media_ref, - getattr(resp, "url", current_url), - final_err, - ) - return None, None - if 300 <= resp.status_code < 400: - next_url = self._next_remote_media_url( - str(getattr(resp, "url", current_url)), resp.headers.get("location") - ) - if not next_url: + async with self._http.stream("GET", current_url, follow_redirects=False) as resp: + final_ok, final_err = validate_resolved_url(str(resp.url)) + if not final_ok: + self.logger.warning( + "remote media redirect blocked ref={} final={} reason={}", + media_ref, + resp.url, + final_err, + ) return None, None - current_url = next_url - continue - if resp.status_code >= 400: - self.logger.warning( - "media download failed status={} ref={}", - resp.status_code, - current_url, - ) - return None, None - if len(resp.content) > DINGTALK_MAX_REMOTE_MEDIA_BYTES: - self.logger.warning( - "media download too large ref={} bytes>{}", - current_url, - DINGTALK_MAX_REMOTE_MEDIA_BYTES, - ) - return None, None - return resp.content, (resp.headers.get("content-type") or "") + if 300 <= resp.status_code < 400: + next_url = self._next_remote_media_url( + str(resp.url), resp.headers.get("location") + ) + if not next_url: + return None, None + current_url = next_url + continue + if resp.status_code >= 400: + self.logger.warning( + "media download failed status={} ref={}", + resp.status_code, + current_url, + ) + return None, None + chunks: list[bytes] = [] + total = 0 + async for chunk in resp.aiter_bytes(): + total += len(chunk) + if total > DINGTALK_MAX_REMOTE_MEDIA_BYTES: + self.logger.warning( + "media download too large ref={} bytes>{}", + current_url, + DINGTALK_MAX_REMOTE_MEDIA_BYTES, + ) + return None, None + chunks.append(chunk) + return b"".join(chunks), (resp.headers.get("content-type") or "") self.logger.warning("media download exceeded redirect limit ref={}", media_ref) return None, None except httpx.TransportError: diff --git a/nanobot/channels/dingtalk/tests/test_dingtalk_channel.py b/nanobot/channels/dingtalk/tests/test_dingtalk_channel.py index 4190c4bf4..9cf96bf82 100644 --- a/nanobot/channels/dingtalk/tests/test_dingtalk_channel.py +++ b/nanobot/channels/dingtalk/tests/test_dingtalk_channel.py @@ -1,6 +1,7 @@ import asyncio import json import zipfile +from contextlib import asynccontextmanager from io import BytesIO from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock @@ -45,6 +46,9 @@ class _FakeResponse: self.headers = headers or {"content-type": "application/json"} self.url = httpx.URL(url) + async def aiter_bytes(self): + yield self.content + def json(self) -> dict: return self._json_body @@ -59,6 +63,11 @@ class _FakeHttp: return self._responses.pop(0) return _FakeResponse() + @asynccontextmanager + async def stream(self, method, url, **kwargs): + assert method == "GET" + yield await self.get(url, **kwargs) + async def post(self, url: str, json=None, headers=None, **kwargs): self.calls.append( {"method": "POST", "url": url, "json": json, "headers": headers, "kwargs": kwargs} @@ -1267,7 +1276,7 @@ async def test_send_media_ref_short_circuits_on_download_transport_error() -> No channel = DingTalkChannel(config, MessageBus()) # First POST (sampleImageMsg) returns API error → False, then GET (download) raises transport error - class _MixedHttp: + class _MixedHttp(_FakeHttp): def __init__(self) -> None: self.calls: list[dict] = [] @@ -1299,7 +1308,7 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None image_bytes = b"\xff\xd8\xff\xe0" + b"\x00" * 100 # minimal JPEG-ish data - class _UploadFailsHttp: + class _UploadFailsHttp(_FakeHttp): def __init__(self) -> None: self.calls: list[dict] = [] @@ -1326,3 +1335,29 @@ async def test_send_media_ref_short_circuits_on_upload_transport_error() -> None # POST (image URL), GET (download), POST (upload) attempted — no further sends methods = [c["method"] for c in channel._http.calls] assert methods == ["POST", "GET", "POST"] + + +async def test_remote_media_stops_reading_at_limit_and_closes_stream(monkeypatch): + monkeypatch.setattr(dingtalk_module, "DINGTALK_MAX_REMOTE_MEDIA_BYTES", 8) + channel = DingTalkChannel( + DingTalkConfig(client_id="app", client_secret="secret", allow_from=["*"]), + MessageBus(), + ) + + class BoundedStream(httpx.AsyncByteStream): + closed = False + + async def __aiter__(self): + yield b"12345" + yield b"6789" + raise AssertionError("must stop consuming when the size limit is exceeded") + + async def aclose(self): + self.closed = True + + body = BoundedStream() + transport = httpx.MockTransport(lambda request: httpx.Response(200, stream=body)) + async with httpx.AsyncClient(transport=transport) as client: + channel._http = client + assert await channel._fetch_remote_media_bytes("https://example.com/large") == (None, None) + assert body.closed