Skip to content

Three things the gateway was letting past it - #84

Merged
blakebauman merged 1 commit into
mainfrom
fix/connection-meta-and-upstream-bounds
Aug 25, 2026
Merged

blakebauman merged 1 commit into
mainfrom
fix/connection-meta-and-upstream-bounds

Conversation

@blakebauman

Copy link
Copy Markdown
Member

Three defects, found while auditing fold's feature surface against a peer implementation. Each is independent; they ship together because they are all "the gateway relayed something it should have stopped," and none is large.

1. Connection-owned _meta keys crossed the proxy hop

The MCP _meta map carries keys describing the connection a request arrived on — io.modelcontextprotocol/protocolVersion, /clientInfo, /clientCapabilities. Behind a gateway there are two connections, so a key that was true on the way in is false on the way out. fold forwarded them unchanged.

The SDK makes this consequential in both directions: its client fills those keys on an outgoing request only when absent (mcp/client.go), and its server prefers a request's _meta to the session's own initialize params (ServerRequest.ClientCapabilities() and friends). So a value forwarded from the caller wins over the one fold negotiated, and the upstream is told the wrong protocol version, the wrong client identity, and capabilities fold has no session to bridge.

fold already made this argument at initialize — capProfile is computed from the extension identifiers fold implements rather than from the map the client sent, precisely so a caller inventing extension ids cannot mint sessions. The per-request path bypassed the same guard.

Stripped on all four typed paths plus the opaque task-params path, and serverInfo stripped in the reverse direction, where leaving it in place both reached the caller and suppressed fold's own identity stamp. Every other key — progress tokens, trace context, task and app metadata, vendor keys — is untouched.

Two subtleties worth review:

  • The byte-scan fast path on the task blob is sound only because it also requires the absence of a backslash. JSON permits any character in a key to be written as an escape, so "io.modelcontextprotocol/protocolVersion" (and the \/ spelling) decode to exactly the key being removed while containing none of its bytes. Without the backslash condition a caller escapes one letter and the strip is skipped.
  • Once that path parses, it re-marshals unconditionally. Returning the original bytes on a "nothing found" result reopens the hole via duplicate members: {"_meta":{<key>},"_meta":{"x":1}} decodes under Go's last-wins rule to a map with no connection key, so the check passes and the first _meta goes out intact — readable by any upstream whose parser takes the first member.

On today's protocol era only a hand-rolled client can set these keys. On 2026-07-28 the SDK marks clientCapabilities Required: Yes on every request, so this is prerequisite work rather than hardening.

2. EMA advertised an authorization server that answered 404

With the embedded token endpoint enabled, fold names itself in authorization_servers in its RFC 9728 protected-resource metadata — and published no RFC 8414 document. A client following that pointer found nothing, so the token endpoint had to be configured out of band, which defeats advertising it.

Now published at /.well-known/oauth-authorization-server, and at the RFC 8414 §3.1 path-scoped form when auth.resource carries a path, since that is where a conforming client looks. Endpoints derive from the issuer's origin rather than concatenating onto it: a canonical MCP resource identifier commonly includes a path, and …/mcp/oauth/token is not where fold serves anything — and per §3.3 an issuer mismatch makes a conforming client reject the whole document.

Also: assertions typed as OAuth access tokens (at+jwt, RFC 9068 makes it a MUST) are refused at the token endpoint. Nothing legitimately presented as an identity assertion carries that type, and accepting them let a token minted for the gateway's audience be redeemed as a grant.

The stricter SEP-990 check — requiring typ: oauth-id-jag+jwt — is deliberately not here, and auth/ema.go records why and what stays open: JWT libraries stamp typ: "JWT" unless told otherwise, so a positive requirement cannot be a silent default change under the v1 contract. It needs a config field. The residual risk is stated in the code rather than implied away.

3. Nothing bounded what an upstream could return

server.maxBodyBytes has capped the inbound direction since v1, and everything else fold fetches — tokens, JWKS, the discovery document, the decision hook — carries its own limit. The upstream data path had none: an oversized tools/list is decoded, then cached, and with server.redisUrl set pushed into shared fleet state. Unbounded memory keyed by something the gateway does not choose, which is the rule internal/bounded exists to enforce everywhere else.

upstreams[].maxResponseBytes, default 64 MiB — far above any real payload, because this is a backstop rather than a size policy. Negative restores the previous behaviour.

  • Refuses rather than truncates. A shortened body would be a response the upstream never sent, so the call fails -32041 and nothing partial is served or cached. Read returns 0 once capped, not a prefix.
  • Per event on text/event-stream, not per connection — a subscription open for a day is legitimately unbounded in total, so a connection-wide cap would cut healthy traffic at an arbitrary hour.
  • A value below 64 KiB is refused at startup. "maxResponseBytes": 64 meaning MiB would fail every call and open the breaker, reading as an outage rather than a typo.

New metric fold_upstream_response_capped_total{upstream}, with an alert in both shipped rule files.

Defaults

This adds one default where there was none (64 MiB). The v1 contract freezes defaults, and a new field has no prior default — but a cap that trips is still a behaviour change on upgrade, so it is argued rather than assumed, in docs/defaults.md. The reasoning: unbounded memory keyed by something fold does not choose is a defect, not a configured choice.

Verification

  • go test -race ./... — all packages green
  • conformance 40/40
  • bench: 0.172 ms added p50 (gate 5 ms) — the meta fast path and the body wrapper cost nothing measurable
  • golangci-lint 0 issues, gofmt / vet / tidy clean, helm-check ok

Roughly two-thirds of the diff is tests. Notable coverage: the allocation-free fast path is pinned by pointer identity so it cannot silently regress; the SSE per-event bound and the frame-terminator straddle are mutation-checked; and FuzzSanitizeRawMeta asserts that no decoded connection key survives for any input.

Two gaps stated rather than hidden: forged protocolVersion cannot be exercised end-to-end (the SDK's stateful server rejects it with a 400 before fold's router sees it, so fold's strip there is defense-in-depth and unit-tested only), and the 64 MiB default is not exercised because it would need a 64 MiB fixture — only explicit values are.

🤖 Generated with Claude Code

Connection-owned `_meta` keys crossed the proxy hop verbatim. The MCP
`_meta` map carries keys that describe the connection a request arrived
on — protocolVersion, clientInfo, clientCapabilities — and behind a
gateway there are two connections, so a key that was true inbound is
false outbound. The SDK makes that consequential in both directions: its
client fills those keys only when absent, and its server prefers a
request's `_meta` to the session's own initialize params, so a value
forwarded from the caller wins over the one fold negotiated and the
upstream believes it. fold already refused to relay a client's raw
declaration at initialize, computing the capability profile from the
extension identifiers it implements rather than from the map the client
sent; this is the same argument on the per-request path, which that
guard did not cover. All four typed paths and the opaque task-params
path strip them now, and an upstream's serverInfo is stripped in the
reverse direction, where leaving it both reached the caller and
suppressed fold's own identity.

Two details the implementation had to get right. The raw task path
forwards bytes rather than structs, so the strip is gated on a byte
scan — and the gate is sound only because it also requires the absence
of a backslash: JSON lets any character in a key be written as an
escape, so "io.modelcontextprotocol/protocolVersion" decodes to the
key being removed while containing none of its bytes. And once that path
parses, it re-marshals unconditionally, because returning the original
bytes on a no-op would reopen the hole by way of duplicate members: Go
takes the last, an upstream taking the first would read the key fold
believed it had removed.

EMA advertised an authorization server that answered 404. With the
embedded token endpoint on, fold names itself in `authorization_servers`
in its RFC 9728 metadata and then published no RFC 8414 document, so the
pointer led nowhere and the token endpoint had to be configured out of
band. It is published now, at the root path and at the RFC 8414 §3.1
path-scoped form when auth.resource carries a path. Endpoints derive
from the issuer's origin rather than concatenating onto it, since a
canonical MCP resource identifier commonly has a path and fold serves
nothing under it. Assertions typed as OAuth access tokens (at+jwt) are
refused: nothing legitimately presented as an identity assertion carries
that type, and accepting them let a token minted for the gateway's
audience be redeemed as a grant.

Nothing bounded what an upstream could return. The inbound direction has
had a cap since v1 and everything else fold fetches carries one; the
upstream data path had none, so an oversized list was decoded, cached,
and with Redis configured pushed into shared fleet state — unbounded
memory keyed by something the gateway does not choose. maxResponseBytes
bounds it at 64 MiB by default, far above any real payload because it is
a backstop rather than a size policy. It refuses rather than truncates,
since a shortened body would be a response the upstream never sent. On
an event stream the bound is per event, not per connection, because a
subscription open for a day is legitimately unbounded in total. A value
under 64 KiB is refused at startup: every call failing and the breaker
opening does not read as a typo.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@blakebauman
blakebauman merged commit 1a42099 into main Aug 25, 2026
8 checks passed
@blakebauman
blakebauman deleted the fix/connection-meta-and-upstream-bounds branch August 25, 2026 21:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant