Skip to content

fix: give caller-derived upstreams their own session per principal - #67

Closed
blakebauman wants to merge 1 commit into
fix/health-skip-caller-derivedfrom
feat/per-caller-upstream-sessions
Closed

blakebauman wants to merge 1 commit into
fix/health-skip-caller-derivedfrom
feat/per-caller-upstream-sessions

Conversation

@blakebauman

Copy link
Copy Markdown
Member

Stacked on #66 — base is fix/health-skip-caller-derived because this builds on the callerDerived() helper that PR introduces. GitHub will retarget to main once #66 merges.

The bug

Attaching a credential per outgoing request is necessary but not sufficient, and the gateway's own bookkeeping looks correct either way — which is why this survived.

credentialTransport.RoundTrip really does resolve credentials from req.Context() on every request (gateway/upstream.go:339-361). But the shared rootSession connects lazily under whichever caller arrived first (:612-618), and the SDK detaches that context with xcontext.Detach, which preserves context values and drops only cancellation. Its own comment says why:

// allows us to preserve context values (which may be necessary for auth
// middleware), yet only cancel the standalone stream when the connection is closed.
connCtx, cancel := context.WithCancel(xcontext.Detach(ctx))   // mcp/streamable.go:2031

So the connection context permanently holds the first caller's *auth.Principal:

  • initialize is credentialed by caller A, so the upstream mints a session bound to A
  • the standalone SSE GET is opened — and re-opened on every reconnect, indefinitely — with A's credential
  • when A's exchanged token expires, fold re-exchanges using A's fold JWT captured in that detached context, long after A logged out

Everything through u.do → rootSession inherits it: all four list methods, resources/read, subscribe, completion/complete, tasks/*. On the wire the upstream sees a session established by A carrying POSTs bearing B's token, and resolves it either way:

  • honors the session identity → B is served A's view
  • rejects the mismatch → not a *jsonrpc.Error, so guardedDo records a breaker failure (:850) and five of them open the circuit for every caller of that upstream

The tell that this was unfinished rather than intended: UpstreamCredentials.PerRequest() (auth/upstream.go:291) — the one function that asks "is this credential caller-derived, so it must be attached per request rather than per session?" — was dead code until #66. The property only ever gated the list-cache kill and an auth.mode validation. The session question it names was never wired up.

The fix

Key the root session by (issuer, subject) — the same key the exchanged-token cache already uses — whenever the credential is caller-derived; keep the single shared session otherwise, so nothing changes for an upstream whose identity is the same whoever asks.

  • u.session + u.subscribed become u.roots map[string]*rootEntry, with sharedRootKey ("") for the shared case, so both paths are one mechanism rather than two.
  • The entry outlives its session: dropSession clears session but keeps the entry, because its subscribed set is what replays that caller's subscriptions onto the reconnect.
  • subscribedURIs unions across entries (reload carry-over) and isSubscribed reports whether any session holds the URI, which is the question the downstream ref-count actually asks.
  • Per-caller entries age out on the idle sweep that already bounds bridged sessions — they are keyed by a verified principal, an identifier the gateway does not choose. The shared root is never swept.

Tests

  • TestCallerDerivedUpstreamsGetTheirOwnSession — the gate. It asserts at the upstream, which is the only vantage point where the crossing is observable: no upstream session may ever see two caller credentials. Verified to fail on the pre-fix behavior:
    --- FAIL: TestCallerDerivedUpstreamsGetTheirOwnSession
        upstream session "OFYA5FYWWOYHH6NWFSYVBX7MAN" served 2 different callers
    
  • TestConfiguredCredentialUpstreamsStillShareOneSession — the partitioning is confined to caller-derived credentials; a static upstream still opens exactly one.
  • TestPerCallerSessionsAreSweptWhenIdle — the map is bounded and the shared root survives.

Gate

go test -race ./... clean, golangci-lint 0 issues, conformance 40/40 (including resources-subscribe / resources-unsubscribe, which exercise the refactored subscription state), and the latency gate is unmoved:

BENCH_RESULT added_p50=182µs direct_p50=116.625µs gateway_p50=298.625µs gateway_p99=719.125µs

The shared path returns its key without touching the context, so the hot path for an ordinary federation is unchanged.

Docs

docs/security-model.md credential-containment section and docs/configuration.md's upstream-auth notes.

🤖 Generated with Claude Code

Attaching a credential per outgoing request is necessary but not sufficient.
The MCP session itself is established by whichever caller happens to open it,
and that identity is durable: the SDK detaches the connection context but
deliberately preserves its values, so the initialize, the standalone SSE
stream, and every reconnect of that stream carry the opening caller's
credential for as long as the connection lives.

A shared root session under passthrough or token-exchange therefore presents
one caller's identity to the upstream while carrying another's bearer on the
request. An upstream that scopes anything to the session it minted — the
normal thing for a server that authenticates — is entitled to resolve that
either way: serve the wrong caller's view, or reject the mismatch, which
guardedDo records as a breaker failure until the circuit opens for everyone.
It also means fold keeps re-minting a departed caller's exchanged token from
the credential captured in that detached context, indefinitely.

Key the root session by (issuer, subject) — the same key the exchanged-token
cache uses — whenever the credential is caller-derived, and keep the single
shared session otherwise, so nothing changes for an upstream whose identity
is the same whoever asks. The subscription set moves onto the session entry,
which now outlives its session so a reconnect replays what that caller
established. Per-caller entries age out on the idle sweep that already bounds
bridged sessions, since they are keyed by an identifier the gateway does not
choose; the shared root is never swept.

The regression gate asserts at the upstream, which is the only vantage point
where the crossing is visible: no upstream session may ever see two different
caller credentials.

Added p50 is unchanged at 182µs (gate 5ms) — the shared path returns its key
without touching the context — and conformance stays 40/40.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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