|
| 1 | +"""Surface the server's error body on failed HTTP calls. |
| 2 | +
|
| 3 | +``aiohttp.ClientResponse.raise_for_status()`` raises a ``ClientResponseError`` |
| 4 | +whose ``message`` is only the reason phrase ("Forbidden"). Servers put the |
| 5 | +real reason in the response body, typically ``{"error": "..."}``, and that |
| 6 | +was discarded, so a refused call or discovery surfaced as nothing more than a |
| 7 | +status code. Mirrors the TypeScript SDK's ``_normalizeToolError``. |
| 8 | +""" |
| 9 | +import json |
| 10 | +import re |
| 11 | +from typing import Optional |
| 12 | + |
| 13 | +import aiohttp |
| 14 | + |
| 15 | +# Bodies are folded into an exception message; keep pathological ones bounded. |
| 16 | +MAX_DETAIL_CHARS = 2000 |
| 17 | + |
| 18 | +# How much of an error body is read at all. The response may come from an |
| 19 | +# attacker-controlled endpoint (discovery URLs are exactly that trust |
| 20 | +# surface), so the read is bounded up front rather than buffered in full and |
| 21 | +# truncated afterwards. Comfortably larger than MAX_DETAIL_CHARS so a JSON |
| 22 | +# body with a long ``error`` field still parses. |
| 23 | +MAX_BODY_READ_BYTES = 64 * 1024 |
| 24 | + |
| 25 | +_DETAIL_KEYS = ("error", "message", "detail") |
| 26 | + |
| 27 | +# Control characters (newlines, ANSI escape introducers, NUL) are collapsed so |
| 28 | +# server-controlled text folded into an exception message or a log line cannot |
| 29 | +# forge extra log records or terminal escape sequences. |
| 30 | +# C0 and C1 control ranges: C1 (U+0080..U+009F) carries escape introducers too. |
| 31 | +_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]+") |
| 32 | + |
| 33 | + |
| 34 | +def _clean(text: str) -> str: |
| 35 | + return _CONTROL_CHARS.sub(" ", text).strip()[:MAX_DETAIL_CHARS] |
| 36 | + |
| 37 | + |
| 38 | +def error_detail_from_body(text: str) -> Optional[str]: |
| 39 | + """Extract a human-readable reason from an error response body. |
| 40 | +
|
| 41 | + When the body is a JSON object, the first of ``error`` / ``message`` / |
| 42 | + ``detail`` that is present decides: a non-empty string is returned as the |
| 43 | + reason; anything else (an object, a list, a number) means the server sent a |
| 44 | + structured error, so the raw JSON is returned to keep that structure |
| 45 | + visible rather than skipping ahead to a lower-priority generic string. |
| 46 | + A non-JSON body is returned as-is. Returns ``None`` for an empty body. |
| 47 | + """ |
| 48 | + body = text.strip() |
| 49 | + if not body: |
| 50 | + return None |
| 51 | + try: |
| 52 | + data = json.loads(body) |
| 53 | + except (ValueError, RecursionError): |
| 54 | + # RecursionError: a deeply nested body ("[[[[...") within the read cap |
| 55 | + # can exceed the parser's recursion limit; it is still just text. |
| 56 | + return _clean(body) |
| 57 | + if isinstance(data, dict): |
| 58 | + for key in _DETAIL_KEYS: |
| 59 | + if key not in data or data[key] is None: |
| 60 | + continue |
| 61 | + value = data[key] |
| 62 | + if isinstance(value, str): |
| 63 | + if value.strip(): |
| 64 | + return _clean(value) |
| 65 | + continue |
| 66 | + # Structured error: show it rather than a later generic string. |
| 67 | + return _clean(body) |
| 68 | + return _clean(body) |
| 69 | + |
| 70 | + |
| 71 | +async def _read_body_bounded(response: aiohttp.ClientResponse, limit: int) -> str: |
| 72 | + """Read at most ``limit`` bytes of the body and decode them leniently.""" |
| 73 | + chunks = [] |
| 74 | + total = 0 |
| 75 | + async for chunk in response.content.iter_chunked(8192): |
| 76 | + chunks.append(chunk) |
| 77 | + total += len(chunk) |
| 78 | + if total >= limit: |
| 79 | + break |
| 80 | + raw = b"".join(chunks)[:limit] |
| 81 | + # ``charset`` only parses the Content-Type header, but stay defensive: the |
| 82 | + # body was read directly, so aiohttp's own buffered-body machinery must not |
| 83 | + # be relied on, and an unknown charset name must not lose the detail. |
| 84 | + try: |
| 85 | + return raw.decode(response.charset or "utf-8", errors="replace") |
| 86 | + except (LookupError, RuntimeError, ValueError): |
| 87 | + return raw.decode("utf-8", errors="replace") |
| 88 | + |
| 89 | + |
| 90 | +async def raise_for_status_with_body(response: aiohttp.ClientResponse) -> None: |
| 91 | + """Like ``response.raise_for_status()``, but with the response body in the error. |
| 92 | +
|
| 93 | + On a 4xx/5xx, reads up to ``MAX_BODY_READ_BYTES`` of the body and raises a |
| 94 | + ``ClientResponseError`` of the same status and headers whose ``message`` is |
| 95 | + ``"<reason>: <detail>"``. The text that was read is attached as ``body`` |
| 96 | + for callers that want the structure. Does nothing on a 2xx/3xx. |
| 97 | + """ |
| 98 | + if response.status < 400: |
| 99 | + return |
| 100 | + try: |
| 101 | + text = await _read_body_bounded(response, MAX_BODY_READ_BYTES) |
| 102 | + except Exception: |
| 103 | + text = "" |
| 104 | + detail = error_detail_from_body(text) |
| 105 | + reason = response.reason or "" |
| 106 | + message = f"{reason}: {detail}" if detail else reason |
| 107 | + error = aiohttp.ClientResponseError( |
| 108 | + response.request_info, |
| 109 | + response.history, |
| 110 | + status=response.status, |
| 111 | + message=message, |
| 112 | + headers=response.headers, |
| 113 | + ) |
| 114 | + error.body = text # type: ignore[attr-defined] |
| 115 | + raise error |
0 commit comments