Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions gateway/relay/media.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,13 @@ def _post() -> Optional[str]:
import json

body = json.loads(resp.read().decode("utf-8"))
# A well-behaved connector returns a JSON object, but a
# valid-JSON non-object (null, [], a string) would make
# `.get` raise AttributeError — which escapes the except
# below and breaks the best-effort contract. Treat any
# non-object body as a failure.
if not isinstance(body, dict):
return None
media_id = body.get("id")
if not media_id:
return None
Expand Down
24 changes: 24 additions & 0 deletions tests/gateway/relay/test_relay_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,27 @@ async def test_client_upload_rejects_oversize_and_missing(tmp_path: Path):
empty = tmp_path / "empty.bin"
empty.write_bytes(b"")
assert await c.upload(str(empty)) is None


@pytest.mark.asyncio
@pytest.mark.parametrize("payload", [b"null", b"[]", b'"ok"', b"42"])
async def test_client_upload_non_object_response_returns_none(tmp_path: Path, payload: bytes):
"""A valid-JSON non-object response is a failure, not a crash.

`upload()` promises None on any failure; a body like `null`/`[]` used to
reach `.get` and raise AttributeError (outside the caught tuple), escaping
into the send path instead of degrading to the caller's fallback.
"""
from unittest.mock import MagicMock, patch

src = tmp_path / "a.png"
src.write_bytes(b"x")
c = RelayMediaClient("https://c.example", "gw1", "sec")

resp = MagicMock()
resp.read.return_value = payload
resp.__enter__.return_value = resp
resp.__exit__.return_value = False

with patch("urllib.request.urlopen", return_value=resp):
assert await c.upload(str(src)) is None