-
Notifications
You must be signed in to change notification settings - Fork 48
http: surface the server's error body on failed calls and discovery #102
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
104 changes: 104 additions & 0 deletions
104
plugins/communication_protocols/http/src/utcp_http/_errors.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """Surface the server's error body on failed HTTP calls. | ||
|
|
||
| ``aiohttp.ClientResponse.raise_for_status()`` raises a ``ClientResponseError`` | ||
| whose ``message`` is only the reason phrase ("Forbidden"). Servers put the | ||
| real reason in the response body, typically ``{"error": "..."}``, and that | ||
| was discarded, so a refused call or discovery surfaced as nothing more than a | ||
| status code. Mirrors the TypeScript SDK's ``_normalizeToolError``. | ||
| """ | ||
| import json | ||
| from typing import Optional | ||
|
|
||
| import aiohttp | ||
|
|
||
| # Bodies are folded into an exception message; keep pathological ones bounded. | ||
| MAX_DETAIL_CHARS = 2000 | ||
|
|
||
| # How much of an error body is read at all. The response may come from an | ||
| # attacker-controlled endpoint (discovery URLs are exactly that trust | ||
| # surface), so the read is bounded up front rather than buffered in full and | ||
| # truncated afterwards. Comfortably larger than MAX_DETAIL_CHARS so a JSON | ||
| # body with a long ``error`` field still parses. | ||
| MAX_BODY_READ_BYTES = 64 * 1024 | ||
|
|
||
| _DETAIL_KEYS = ("error", "message", "detail") | ||
|
|
||
|
|
||
| def error_detail_from_body(text: str) -> Optional[str]: | ||
| """Extract a human-readable reason from an error response body. | ||
|
|
||
| When the body is a JSON object, the first of ``error`` / ``message`` / | ||
| ``detail`` that is present decides: a non-empty string is returned as the | ||
| reason; anything else (an object, a list, a number) means the server sent a | ||
| structured error, so the raw JSON is returned to keep that structure | ||
| visible rather than skipping ahead to a lower-priority generic string. | ||
| A non-JSON body is returned as-is. Returns ``None`` for an empty body. | ||
| """ | ||
| body = text.strip() | ||
| if not body: | ||
| return None | ||
| try: | ||
| data = json.loads(body) | ||
| except ValueError: | ||
| return body[:MAX_DETAIL_CHARS] | ||
| if isinstance(data, dict): | ||
| for key in _DETAIL_KEYS: | ||
| if key not in data or data[key] is None: | ||
| continue | ||
| value = data[key] | ||
| if isinstance(value, str): | ||
| if value.strip(): | ||
| return value.strip()[:MAX_DETAIL_CHARS] | ||
| continue | ||
| # Structured error: show it rather than a later generic string. | ||
| return body[:MAX_DETAIL_CHARS] | ||
| return body[:MAX_DETAIL_CHARS] | ||
|
|
||
|
|
||
| async def _read_body_bounded(response: aiohttp.ClientResponse, limit: int) -> str: | ||
| """Read at most ``limit`` bytes of the body and decode them leniently.""" | ||
| chunks = [] | ||
| total = 0 | ||
| async for chunk in response.content.iter_chunked(8192): | ||
| chunks.append(chunk) | ||
| total += len(chunk) | ||
| if total >= limit: | ||
| break | ||
| raw = b"".join(chunks)[:limit] | ||
| # ``charset`` only parses the Content-Type header, but stay defensive: the | ||
| # body was read directly, so aiohttp's own buffered-body machinery must not | ||
| # be relied on, and an unknown charset name must not lose the detail. | ||
| try: | ||
| encoding = response.charset or "utf-8" | ||
| raw.decode(encoding, errors="replace") | ||
| except (LookupError, RuntimeError, ValueError): | ||
| encoding = "utf-8" | ||
| return raw.decode(encoding, errors="replace") | ||
|
|
||
|
|
||
| async def raise_for_status_with_body(response: aiohttp.ClientResponse) -> None: | ||
| """Like ``response.raise_for_status()``, but with the response body in the error. | ||
|
|
||
| On a 4xx/5xx, reads up to ``MAX_BODY_READ_BYTES`` of the body and raises a | ||
| ``ClientResponseError`` of the same status and headers whose ``message`` is | ||
| ``"<reason>: <detail>"``. The text that was read is attached as ``body`` | ||
| for callers that want the structure. Does nothing on a 2xx/3xx. | ||
| """ | ||
| if response.status < 400: | ||
| return | ||
| try: | ||
| text = await _read_body_bounded(response, MAX_BODY_READ_BYTES) | ||
| except Exception: | ||
| text = "" | ||
| detail = error_detail_from_body(text) | ||
| reason = response.reason or "" | ||
| message = f"{reason}: {detail}" if detail else reason | ||
| error = aiohttp.ClientResponseError( | ||
| response.request_info, | ||
| response.history, | ||
| status=response.status, | ||
| message=message, | ||
| headers=response.headers, | ||
| ) | ||
| error.body = text # type: ignore[attr-defined] | ||
| raise error |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2:
raise_for_status_with_bodybuffers the whole error body withawait response.text()beforeerror_detail_from_bodytruncates the message. The 2000-char cap (MAX_DETAIL_CHARS) only bounds the folded message, not the memory used to read it, so a provider (including an attacker-controlled discovery endpoint, the same trust surface handled elsewhere in this file) returning an arbitrarily large 4xx/5xx body causes an unbounded in-memory buffer on every failed call. Previouslyresponse.raise_for_status()never touched the body. Read the body incrementally against the cap (e.g.response.content.iter_chunked) and stop once MAX_DETAIL_CHARS bytes are collected.Prompt for AI agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Valid, fixed: the body is now read with iter_chunked and the read stops at MAX_BODY_READ_BYTES (64 KiB), decoded leniently with the response charset, so the cap bounds memory and not just the message. Test added with a 1 MiB error body asserting both the read and the message stay bounded.