Skip to content

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

Merged
blakebauman merged 3 commits into
mainfrom
feat/per-caller-upstream-sessions
Aug 14, 2026
Merged

blakebauman merged 3 commits into
mainfrom
feat/per-caller-upstream-sessions

Conversation

@blakebauman

Copy link
Copy Markdown
Member

Supersedes #67, which GitHub auto-closed when its base branch (#66) was deleted on merge. Same branch, same commits, now targeting main.

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. But the shared rootSession connects lazily under whichever caller arrived first, 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 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.

Note on the merge commit

bac5617 merges main with the ours strategy. #66 landed as a squash, so its commits are not ancestors of this branch and git saw both sides editing the lines it introduced. The branch tree already contained main's content in full — verified by diffing the trees, which showed only this PR's four files — so the merge records the ancestry and keeps the branch tree unchanged.

Docs

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

🤖 Generated with Claude Code

blakebauman and others added 3 commits August 13, 2026 17:53
A health probe runs on nobody's behalf, so an upstream using passthrough or
token-exchange has no credential to present: creds.Apply fails, the connect
fails, and guardedDo charges that failure to the upstream. Every poll then
consumed its rate budget, recorded a circuit-breaker failure — five polls
open the circuit for the clients it serves perfectly well — and, once a real
session existed, charged the upstream and server budgets for traffic no
caller asked for. /health reported healthy == 0 and answered 503, so a
gateway whose federation is entirely caller-derived never became Ready while
serving every authenticated caller correctly. The active probe loop had the
same defect and worse: probeEndpoints runs on context.Background(), so it
ejected every endpoint on its first round.

Report such an upstream "unprobed" rather than down, count it as neither
healthy nor unhealthy, and judge the 503 against what the gateway can
actually reach. healthCheck is likewise ignored for them, with a warning at
startup rather than a validation error so an existing config keeps serving.

The unprobed flag is omitempty, so a federation without caller-derived
credentials keeps the exact response shape it had. This also makes
UpstreamCredentials.PerRequest — until now dead code — load-bearing.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
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]>
#66 landed as a squash, so its commits are not ancestors of this branch and
git sees both sides editing the lines it introduced. This branch already
contains main's content in full — verified by diffing the trees — plus this
PR's changes, so the merge keeps the branch tree as-is.
@blakebauman
blakebauman merged commit d5995e8 into main Aug 14, 2026
7 checks passed
@blakebauman
blakebauman deleted the feat/per-caller-upstream-sessions branch August 14, 2026 01:11
blakebauman added a commit that referenced this pull request Aug 14, 2026
Covers #65, #66 and #68. Filed under "Unreleased" rather than a dated
version: entries here are written as part of a release and land in the
release commit, so a dated heading on main before the tag is the exact
drift the release runbook warns about. It becomes the version heading when
these ship.

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
blakebauman added a commit that referenced this pull request Aug 14, 2026
Dates the changelog entry for the three caller-derived credential fixes
(#65, #66, #68) and bumps the chart: appVersion to v1.12.1, which is what a
default helm install deploys, and the chart's own version to 0.2.2, since a
published OCI tag is immutable.

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