Skip to content

Validate upstream JSON-RPC responses in transparent proxy - #7317

Merged
ChrisJBurns merged 2 commits into
mainfrom
ChrisJBurns/pr-5288-fix-verify
Nov 26, 2026
Merged

ChrisJBurns merged 2 commits into
mainfrom
ChrisJBurns/pr-5288-fix-verify

Conversation

@ChrisJBurns

Copy link
Copy Markdown
Collaborator

Summary

The transparent proxy forwards whatever the backend returns. A broken backend's malformed answer to a JSON-RPC request (missing "jsonrpc":"2.0", invalid id, a bare array or string, an empty body) therefore reaches the client as a successful 200. The client gets a protocol violation instead of a clear upstream error. This takes over #5288 by @bishnubista, who is credited as co-author. That PR identified the gap but needed rework before it could merge (see reviewer notes).

  • In tracingTransport.RoundTrip, check the backend's 200 application/json answer to every id-bearing POST. Replace an invalid one with 502 Bad Gateway and a JSON-RPC error that echoes the client's request id (built with mcp.EncodeJSONRPCError, -32603, fixed message, no upstream headers). Log one WARN naming the reason, method and target.
  • Run the check before the response can register a proxy session or mark the server initialized, so a malformed initialize does neither.
  • Add mcp.ValidateResponse, which applies the existing MCP envelope rules (BOM, string/int64 ids, id-less error responses allowed; batches, requests, notifications, null/fractional ids, duplicate or case-aliased envelope members rejected). It checks the envelope only, so case-distinct names inside result (e.g. a schema with both ID and id) are not rejected.
  • Withhold the client's Accept-Encoding from id-bearing requests, following mcp.WithoutAcceptEncoding in the authz and tool filters, so Go's transport decodes gzip and the body can be checked. A body that still carries a content coding fails closed, as in the authz response filter. Bodies are buffered up to 100 MiB, matching pkg/vmcp/client.
  • Fix the health_check_zombie e2e mock, which answered every POST without an id.

Fixes #5247

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test). Everything passes except 4 tests in pkg/plugins/pluginsvc, which also fail on main in the same local environment and are unrelated.
  • E2E tests (task test-e2e)
  • Linting (task lint-fix, with CI's pinned golangci-lint v2.15.0, 0 issues)
  • Manual testing (describe below)

Manual and e2e checks:

Changes

File Change
pkg/mcp/response_validation.go New ValidateResponse, envelope-only response check with fixed rejection reasons
pkg/transport/proxy/transparent/upstream_response.go Gate, bounded buffering, and the synthetic 502
pkg/transport/proxy/transparent/transparent_proxy.go Withhold Accept-Encoding for id-bearing requests; validate before session registration
test/e2e/health_check_zombie_test.go Mock echoes the request id
docs/arch/03-transport-architecture.md, docs/middleware.md Document the check, its 502 shape, and its scope

Does this introduce a user-facing change?

Yes, for clients of the transparent proxy (thv run with streamable-http/SSE servers, remote servers, thv proxy, operator proxy runners):

  • Malformed backend answers. Before: a 200 application/json body that is not a valid JSON-RPC response, answering an id-bearing request, was forwarded as 200. After: 502 Bad Gateway with {"jsonrpc":"2.0","id":<request id>,"error":{"code":-32603,"message":"Invalid upstream JSON-RPC response"}}, plus a WARN log line on the proxy.
  • Compression. Before: the client's Accept-Encoding was forwarded, so the backend could compress responses end to end. After: it is withheld for id-bearing requests, so those responses (JSON and SSE) reach the client uncompressed. A backend that compresses unprompted, or uses a coding Go does not decode (br, zstd), gets its JSON answer rejected with 502.
  • Large responses. Before: a 200 application/json answer of any size was streamed through. After: it is buffered, and an answer over 100 MiB is rejected with 502.
  • Null ids. An answer with "id": null is now rejected. MCP's RequestId cannot be null, though plain JSON-RPC 2.0 allows it for errors.

Special notes for reviewers

  • How this differs from Validate upstream JSON-RPC responses in transparent proxy #5288:
    • It validates in RoundTrip rather than ModifyResponse, so session state isn't committed for a bad initialize.
    • It reuses the MCP envelope rules instead of a hand-rolled validator.
    • It only checks id-bearing requests.
    • It never emits "id": null.
    • It fails closed on encoded bodies instead of skipping them.
  • Not a security control, and documented as such. A malicious backend can still send well-formed malicious content. SSE responses, non-200 statuses, other media types, notifications and client responses are not validated. That covers the gap @amirejaz noted on Validate upstream JSON-RPC responses in transparent proxy #5288: an SSE stream can't be rewritten to a 502 mid-response.
  • Replay paths are out of scope. Responses returned by the backend session recovery paths (reinitializeAndReplay) are not validated. Those paths register their session before returning, and folding validation in there is a larger change. I can do it as a follow-up if wanted.
  • Error code and status, a deliberate deviation. -32603 follows the codebase precedent for backend failures (pkg/transport/proxy/streamable's upstreamErrorResponse). 502 rather than the authz and tool filters' 500 is deliberate: the fault is the upstream's.
  • Memory. Every 200 application/json answer to an id-bearing request is now buffered (bounded at 100 MiB) instead of streamed.

🤖 Generated with Claude Code

The transparent proxy forwarded whatever a backend returned, so a
broken backend's malformed answer to a JSON-RPC request reached the
client as a successful 200. It now checks the 200 application/json
answer to every id-bearing POST before acting on it, and replaces an
invalid one with a 502 carrying a JSON-RPC error that echoes the
client's request id.

The check runs in tracingTransport.RoundTrip, before the response can
register a proxy session or mark the server initialized, and reuses
the MCP envelope rules through a new mcp.ValidateResponse that
inspects the envelope only. The client's Accept-Encoding is withheld
from id-bearing requests so Go's transport decodes gzip and the body
can be read; a body still carrying a content coding fails closed.
Bodies are buffered up to 100 MiB.

This reworks the approach from #5288, which validated in
ModifyResponse after session registration and rejected some
spec-valid responses.

Fixes #5247

Co-authored-by: Bishnu Bista <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Nov 25, 2026
httptest.Server.Close calls CloseIdleConnections on
http.DefaultTransport, so a parallel test reusing a pooled connection
can fail with "CloseIdleConnections called". The new upstream
validation tests close many servers in parallel, which made this hit
TestPrefixHandlers_WellKnownNamespaceCoexistence in CI. Give that test
a dedicated client and the validation tests a dedicated backend
transport, as #6264 did for the dial-error test.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Nov 26, 2026
@codecov

codecov Bot commented Nov 26, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.87629% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.14%. Comparing base (a9e9e48) to head (e8492db).
⚠️ Report is 112 commits behind head on main.

Files with missing lines Patch % Lines
pkg/mcp/response_validation.go 90.69% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7317      +/-   ##
==========================================
+ Coverage   81.25%   82.14%   +0.89%     
==========================================
  Files         880      934      +54     
  Lines       89960    94625    +4665     
==========================================
+ Hits        73099    77734    +4635     
- Misses      16856    16886      +30     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. This fixes #5247 and addresses the open points from #5288:

  • It validates in RoundTrip, before any session is registered.
  • It reuses the existing MCP envelope rules.
  • It never emits "id": null.
  • It fails closed on bodies that still carry a content coding.

The SSE gap is already tracked in #5292.

I built thv from this branch and from its base and ran thv proxy in front of a mock backend and the official Go SDK server. The PR also merges cleanly onto current main, and pkg/mcp/... and pkg/transport/proxy/... pass on the merged result.

Backend answer to tools/list (id 7) base this PR
Issue repro (no jsonrpc, wrong id) 200, forwarded 502, -32603, id 7 echoed, one WARN
Empty body, or HTML labeled application/json 200 502
SSE with a bad frame, or 500 with a non-JSON body passed through passed through (out of scope, as documented)
Gzip-compressing backend client sees gzip Go negotiates and decodes; valid response forwarded
Empty 200 answering a notification 200 200
Malformed initialize returning Mcp-Session-Id session registered 502; a follow-up request with that session id gets 404

Results with the official Go SDK client:

  • Connect, list and call all succeed with a JSON-response server, a gzip-middleware server and an SSE server, at 100 B, 5 MB and 60 MB.
  • At 110 MB the JSON calls now fail with Bad Gateway (body_too_large), while SSE still passes. That matches the documented behavior.
  • On JSON responses, validation costs about 9 ms/MiB.

Two non-blocking notes on existing users:

  1. Backends that serialize the unused member as null now break. Examples: {"jsonrpc":"2.0","id":1,"result":{},"error":null}, or an error response that also carries "result":null. The base branch forwarded these as 200; this PR answers 502. That is strict JSON-RPC (both members present), but it is a likely way a backend that works today starts failing: serializers that don't omit nulls produce exactly this, and lenient clients accept it. Either treat an explicit null for the absent member as absent, or list it under user-facing changes next to null ids, so operators can recognize it from the invalid_response WARN.
  2. A rejected initialize leaves the backend's session open. The backend issued an Mcp-Session-Id that the proxy drops without sending a DELETE, so it lingers until the backend's own idle timeout. That's low impact, and the client can't reuse it (verified above). One line in the scope paragraph would make it explicit.

@ChrisJBurns
ChrisJBurns merged commit c038d02 into main Nov 26, 2026
47 checks passed
@ChrisJBurns
ChrisJBurns deleted the ChrisJBurns/pr-5288-fix-verify branch November 26, 2026 11:53
@rdimitrov

Copy link
Copy Markdown
Member

How this was tested:

Setup: I built thv from this branch and from its base. I ran thv proxy in front of two backends: a mock with one mode per kind of bad reply, and official Go SDK (v1.8.0) streamable servers in three variants (JSON responses, gzip middleware, SSE).

Bad replies (curl, A/B):

  • Rejected with 502 on this branch, forwarded as 200 on base:
    • the issue's reproduction
    • an empty body
    • HTML labeled application/json
    • an explicit "error":null next to result
    • a 200 error reply with "id":null
  • Passed through on both builds:
    • SSE with a bad frame
    • a 500 with a non-JSON body
    • an empty 200 answering a notification
  • A malformed initialize is not registered as a session, so a follow-up request with that session id gets a 404.

Real client: the official Go SDK client ran connect, tools/list and tools/call through both proxies. Replies of 100 B, 5 MB and 60 MB went through all three server variants. At 110 MB, JSON replies return Bad Gateway (body_too_large) and SSE replies still pass, as documented.

Tests: the branch merges cleanly onto current main, and go test ./pkg/mcp/... ./pkg/transport/proxy/... passes on the merged result. -race passes on the touched packages.

ChrisJBurns added a commit that referenced this pull request Nov 26, 2026
Accept null for the unused JSON-RPC member

Upstream response validation rejected responses that carry an explicit
null for the member they do not use, such as {"result":{},"error":null}
or "result":null beside an error. Serializers that do not omit nulls
emit these, lenient clients accept them, and before #7317 the proxy
forwarded them, so a backend that worked would start getting 502s.
They are unambiguous, so treat the null member as absent.

Also document that a rejected initialize response leaves the backend
session it carried open until the backend's idle timeout, since the
proxy does not send it a DELETE.

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

security: proxy forwards malformed upstream JSON-RPC frames to clients without validation

2 participants