The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(attachments): an oversized attach payload is refused in one sentence naming its size
emozillafacbbb2cd897
diff --git a/tests/tui_gateway/test_tui_gateway_server_attach_errors.py b/tests/tui_gateway/test_tui_gateway_server_attach_errors.pynew file mode 100644index 00000000000..74b46a298b3--- /dev/null+++ b/tests/tui_gateway/test_tui_gateway_server_attach_errors.py@@ -0,0 +1,60 @@+"""An attach payload over its cap is refused in one sentence naming its size and the cap.++``image.attach_bytes`` (native Desktop's remote pastes), ``pdf.attach`` and ``file.attach`` decode+base64 payloads in ``tui_gateway/prompt_attachments.py``, which refuses a payload over its cap+either before decoding (the base64 text is too long) or after. Either way the client reads main's+wording, ``<what> too large (<n> bytes; cap is <m> MB)``.+"""++import base64+import sys+import threading+import types++import pytest++from tui_gateway import server++_MIB = 1024 * 1024+++def session(tmp_path, monkeypatch):+ fake_cli = types.ModuleType("cli")+ fake_cli._IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"}+ monkeypatch.setitem(sys.modules, "cli", fake_cli)+ monkeypatch.setattr(server, "_hermes_home", tmp_path)+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ record = {+ "profile_home": str(tmp_path / "profile"),+ "cwd": str(workspace),+ "attached_images": [],+ "image_counter": 0,+ "running": False,+ "history_lock": threading.Lock(),+ }+ monkeypatch.setattr(server, "_sessions", {"oversize": record})+ return "oversize"+++# One byte over a 1 MiB cap is refused after decoding; 2 MiB is refused from the base64 length.[email protected]("size", [_MIB + 1, 2 * _MIB + 5])+def test_an_oversized_image_names_its_size_and_the_cap(session, monkeypatch, size):+ monkeypatch.setattr(server, "_ATTACH_BYTES_MAX_BYTES", _MIB)+ payload = base64.b64encode(b"\x89PNG\r\n\x1a\n" + b"0" * (size - 8)).decode("ascii")++ reply = server._methods["image.attach_bytes"](1, {"session_id": session, "content_base64": payload})++ assert reply["error"]["code"] == 4018+ assert reply["error"]["message"] == f"image too large ({size} bytes; cap is 1 MB)"++[email protected]("size", [_MIB + 1, 2 * _MIB + 5])+def test_an_oversized_inline_file_names_its_size_and_the_cap(session, monkeypatch, size):+ monkeypatch.setattr(server, "_ATTACHMENT_MAX_BYTES", _MIB)+ data_url = "data:application/octet-stream;base64," + base64.b64encode(b"0" * size).decode("ascii")++ reply = server._methods["file.attach"](1, {"session_id": session, "name": "big.bin", "data_url": data_url})++ assert reply["error"]["message"] == f"attachment too large ({size} bytes; cap is 1 MB)"diff --git a/tui_gateway/prompt_attachments.py b/tui_gateway/prompt_attachments.pyindex e6b7c0560bf..710a03536f1 100644--- a/tui_gateway/prompt_attachments.py+++ b/tui_gateway/prompt_attachments.py@@ -32,8 +32,17 @@ _ATTACHMENT_REF_NEEDS_QUOTING_RE = _re.compile(r"""[\s()\[\]{}<>"'`]""")del _re # bodies are rebound onto server globals: import inside functions only-def _b64_payload(raw: str, data_url_re: str, flags: int, *, max_bytes: int) -> bytes:- """Strip an optional ``data:...;base64,`` wrapper and all whitespace, then strictly decode."""+def _too_large(label: str, size: int, max_bytes: int) -> str:+ """The refusal of a payload over its cap: ``image too large (31457280 bytes; cap is 25 MB)``."""+ return f"{label} too large ({size} bytes; cap is {max_bytes // (1024 * 1024)} MB)"+++def _b64_payload(+ raw: str, data_url_re: str, flags: int, *, max_bytes: int, label: str = "attachment",+) -> bytes:+ """Strip an optional ``data:...;base64,`` wrapper and all whitespace, then strictly decode.+ Over *max_bytes* raises ``OverflowError`` with the refusal, before decoding when the base64+ text is already too long."""import base64 as _base64import re as _recleaned = (raw or "").strip()@@ -41,20 +50,23 @@ def _b64_payload(raw: str, data_url_re: str, flags: int, *, max_bytes: int) -> bcleaned = m.group(1)cleaned = _re.sub(r"\s+", "", cleaned)if len(cleaned) > 4 * ((max_bytes + 2) // 3):- raise OverflowError(f"attachment too large; size limit is {max_bytes} bytes")+ padding = len(cleaned) - len(cleaned.rstrip("="))+ raise OverflowError(_too_large(label, len(cleaned) * 3 // 4 - padding, max_bytes))payload = _base64.b64decode(cleaned, validate=True)if len(payload) > max_bytes:- raise OverflowError(f"attachment too large; size limit is {max_bytes} bytes")+ raise OverflowError(_too_large(label, len(payload), max_bytes))return payload-def _decode_attach_base64(raw: str, *, mime_prefix: str, max_bytes: int) -> bytes | None:+def _decode_attach_base64(+ raw: str, *, mime_prefix: str, max_bytes: int, label: str = "attachment",+) -> bytes | None:"""Decode a (``data:<mime_prefix>...;base64,``-wrapped) payload; None when invalid."""import re as _retry:return _b64_payload(raw, rf"^data:{_re.escape(mime_prefix)}[a-zA-Z0-9.+-]*;base64,(.*)$", _re.DOTALL,- max_bytes=max_bytes)+ max_bytes=max_bytes, label=label)except OverflowError:raiseexcept Exception:@@ -65,9 +77,10 @@ def _decode_attach_payload(rid, raw_b64: str, *, mime_prefix: str, max_bytes: int, label: str, empty_msg: str):"""``(bytes, None)`` or ``(None, error)``: 4017 on bad/empty base64, 4018 over *max_bytes*."""try:- data = _decode_attach_base64(raw_b64, mime_prefix=mime_prefix, max_bytes=max_bytes)+ data = _decode_attach_base64(+ raw_b64, mime_prefix=mime_prefix, max_bytes=max_bytes, label=label)except OverflowError as exc:- return None, _err(rid, 4018, f"{label} too large: {exc}")+ return None, _err(rid, 4018, str(exc))if data is None:return None, _err(rid, 4017, "data is not valid base64")if not data:@@ -213,8 +226,8 @@ def _read_attachment_bytes(path: Path, max_bytes: int) -> bytes:# Bound the actual read, not just stat(): the source can grow after inspection.with path.open("rb") as source:payload = source.read(max_bytes + 1)- if len(payload) > max_bytes:- raise ValueError(f"attachment too large; size limit is {max_bytes} bytes")+ if len(payload) > max_bytes:+ raise ValueError(_too_large("attachment", os.fstat(source.fileno()).st_size, max_bytes))return payload