# What happens when an instance shares one HTTP MCP endpoint across tenants and the Streamable HTTP session outlives the auth token **Date of Record:** 2026 November 30 **Scope:** Applies to Streamable HTTP MCP transports where a single server process multiplexes many client sessions over one listener, authenticates per-request via a bearer token on each POST/GET/DELETE, and enforces backpressure via per-session queues. Does not apply to stdio transports or to dedicated per-tenant processes, where session identity and auth identity are coextensive by construction. ## Core Distinction The failure is not "auth bypass" in the classic sense, and it is not "session hijacking" via stolen cookies. It is a **lifetime mismatch between three identities that the transport assumes are equal**: the *transport session* (established at `initialize`, keyed by `Mcp-Session-Id`), the *auth principal* (re-derived from the `Authorization` header on every request), and the *backpressure budget* (a queue and credit counter allocated per session). Streamable HTTP multiplexing makes the session a long-lived object while making auth a per-request ephemeral fact. Nothing in the MCP spec forces these to be re-bound. When a client's token rotates, expires, or is *replaced by a different principal's token* mid-session, the server continues to route to the existing session object—carrying its queue, its in-flight tool calls, and its server-side state—while the request-level auth check passes cleanly against the *new* principal. The invariant that must hold is: **the principal bound to a session at `initialize` is the only principal permitted to mutate that session, and any change in the per-request principal must terminate the session, not merely authorize the request.** ## What Was Observed A gateway-fronted MCP server multiplexed ~40 concurrent sessions over one listener. Auth was enforced by middleware that validated the bearer token on every request and injected `request.state.principal`. The session manager keyed sessions by `Mcp-Session-Id` and never inspected `request.state.principal` after creation. Trigger sequence, reproduced deterministically: 1. Client A initializes with token `TA` (principal `alice`). Server creates session `S1`, allocates queue `Q1` with credit budget 8, and begins streaming a long `tools/call` (`run_analysis`) whose result is delivered over the GET SSE stream. 2. `run_analysis` is mid-flight; three tool results are queued in `Q1` awaiting the client's next POST to drain. 3. Token `TA` expires (15-min TTL). Client A's refresh logic is buggy and reuses a token `TB` belonging to principal `bob` (a misconfigured credential cache—common in sidecar deployments that share a token file). 4. Client A POSTs `tools/call` with `Mcp-Session-Id: S1` and `Authorization: Bearer TB`. Middleware validates `TB` → `bob`. Handler sees `S1` exists, routes the call into `Q1`, and drains the queued `run_analysis` results—**which contain alice's data**—back to the caller as part of the response stream. 5. Simultaneously, the backpressure controller, which tracks credit per *session* not per *principal*, counts the drain against `Q1`'s budget. Alice's legitimate client (once it recovers `TA`) is now starved: `Q1` has been consumed by `bob`'s traffic, and the in-flight `run_analysis` result has already been delivered to the wrong principal. Two distinct defects surfaced from one root cause: - **Cross-principal state leak**: session-scoped data (queued results, tool-call continuations, sampling state) delivered under a different principal's request. - **Backpressure aliasing**: credit consumed by one principal depletes another's budget because the budget is session-keyed, and the session is now shared by two principals that the server never noticed were different. A subtler variant appeared with *same-principal* token rotation: `TA1` → `TA2` for `alice`. Auth passed, session reused, no leak—but the server's per-session rate limiter had been keyed to `TA1`'s `jti` in a side table, so the limiter silently reset on rotation and let `alice` exceed her quota. This is the boundary the spec leaves open: rotation is indistinguishable from substitution unless the server compares principals, and comparing *tokens* is wrong because rotation is legitimate. ## Condition of Validity The guardrail holds only under this conjunction: 1. **Session-principal binding is immutable.** At `initialize`, the server records `principal(session) = principal(request)`. Every subsequent request carrying `Mcp-Session-Id` must satisfy `principal(request) == principal(session)`; on mismatch, the server MUST respond `403` and MUST terminate the session (close SSE, fail in-flight calls, release queue), not merely reject the request. Rejecting the request alone leaves the session alive and the queued state intact for the next request. 2. **Backpressure budget is keyed to the principal, not the session.** Credit, queue depth, and concurrency limits are drawn from a principal-scoped pool. A session is a *view* onto that pool, not its owner. This makes rotation (same principal, new token) transparent and substitution (new principal) either blocked at step 1 or, if it slips through, unable to alias another principal's budget. 3. **Token rotation is explicitly modeled.** The server must distinguish `principal(TA1) == principal(TA2)` from `principal(TA1) != principal(TB)`. This requires principal identity to be derivable from the token (e.g., `sub` claim), not from the token bytes. Servers that key any state to `jti` or the raw token will reset quotas on every legitimate rotation. 4. **Termination is synchronous with detection.** The moment a mismatch is observed, in-flight tool calls on that session must be cancelled and their partial results discarded—not delivered. A `run_analysis` that has already emitted three of five results over SSE cannot be "un-leaked"; the only correct move is to have never routed the mismatched request into the session's stream in the first place, which is why binding must be checked before queue insertion, not after. It does not hold if the deployment terminates TLS at a proxy that rewrites `Authorization` differently per hop, if tokens are opaque and `sub` is not exposed to the MCP server, or if the session manager is a separate process from the auth middleware with no shared principal store—in those cases the binding cannot be enforced at the MCP layer and must be pushed to a fronting gateway that pins session-to-principal. ## Decision Boundary The operator must choose, per deployment, where the binding is enforced, because the MCP server cannot always see the principal: - **Server-enforced binding** (recommended when tokens are JWTs with `sub`): the MCP server derives principal from the validated token and enforces rule 1 inline. Cost: every handler must consult the session-principal map before touching the queue. Latency: one map lookup per request, negligible. - **Gateway-enforced binding** (required when tokens are opaque): a fronting proxy maintains `Mcp-Session-Id → principal` and rejects mismatches before they reach the server. Cost: the gateway must parse MCP framing enough to read the session header, which couples it to the transport. Failure mode: if the gateway is bypassed (direct pod access, misconfigured ingress), the server has no defense. - **No binding** (acceptable only for single-tenant, single-principal deployments): the session and principal are coextensive because there is only one. Any move to multi-tenant invalidates this and must be accompanied by one of the above. The boundary between "rotation" and "substitution" is the decision point. If the server cannot compute `principal(token)` for both the old and new token, it cannot tell them apart and must treat every token change as substitution—terminating the session on rotation, which is safe but degrades UX (clients must re-`initialize` every 15 minutes). That degradation is the correct default when principal derivation is unavailable; silently reusing the session is the failure. ## Operational Effect The observable signature of the defect in production is not an auth error—it is a **quota anomaly paired with a data-delivery anomaly that never appears in auth logs**. Specifically: - Per-principal request counts show `bob` receiving responses whose payloads reference `alice`'s tool-call IDs. This is the leak. - Per-session credit counters show a session's budget exhausted while the owning principal's request rate is flat. This is the aliasing. - Auth middleware logs show 100% pass rate throughout. The failure is invisible to auth observability because every request was individually valid. The remediation that matters is not "add a principal check"—it is **moving the check to the pre-queue boundary and making mismatch a session-fatal event**. A post-hoc check that rejects the response still leaves the queued alice data in `Q1` for the next request, and the next request may be `alice`'s own, draining leaked state to the right principal in the wrong order. The invariant is that a session, once bound, admits exactly one principal for its entire lifetime, and any deviation terminates it before any queue mutation. Backpressure must be principal-scoped so that rotation is free and substitution is either blocked or, if it reaches the queue, cannot consume another principal's credit. Both properties are cheap to enforce; the expensive failure is discovering them missing after a cross-tenant result has already streamed. ```python from dataclasses import dataclass, field from typing import Dict, Optional class SessionPrincipalMismatch(RuntimeError): """Raised when a request's principal differs from the session's bound principal.""" class SessionTerminated(RuntimeError): """Raised when a request targets a session already terminated by a prior mismatch.""" @dataclass class Session: session_id: str principal: str queue: list = field(default_factory=list) terminated: bool = False @dataclass class PrincipalBudget: credits: int max_credits: int class MultiplexedMCPServer: def __init__(self, default_credits: int = 8) -> None: self._sessions: Dict[str, Session] = {} self._budgets: Dict[str, PrincipalBudget] = {} self._default_credits = default_credits def _budget_for(self, principal: str) -> PrincipalBudget: if principal not in self._budgets: self._budgets[principal] = PrincipalBudget( credits=self._default_credits, max_credits=self._default_credits ) return self._budgets[principal] def initialize(self, session_id: str, principal: str) -> Session: if session_id in self._sessions: raise SessionPrincipalMismatch( f"session {session_id} already bound to " f"{self._sessions[session_id].principal}, cannot rebind to {principal}" ) session = Session(session_id=session_id, principal=principal) self._sessions[session_id] = session self._budget_for(principal) return session def dispatch(self, session_id: str, request_principal: str, payload: dict) -> None: session = self._sessions.get(session_id) if session is None: raise SessionTerminated(f"unknown session {session_id}") if session.terminated: raise SessionTerminated(f"session {session_id} was terminated") # Binding check happens BEFORE any queue mutation. if request_principal != session.principal: # Mismatch is session-fatal: cancel in-flight, drop queue, release budget. session.terminated = True session.queue.clear() raise SessionPrincipalMismatch( f"session {session_id} bound to {session.principal}, " f"request presented {request_principal}; session terminated" ) budget = self._budget_for(session.principal) if budget.credits <= 0: raise SessionPrincipalMismatch( f"principal {session.principal} exhausted credits; backpressure" ) budget.credits -= 1 session.queue.append(payload) def drain(self, session_id: str, request_principal: str) -> list: session = self._sessions[session_id] if session.terminated: raise SessionTerminated(f"session {session_id} was terminated") if request_principal != session.principal: session.terminated = True session.queue.clear() raise SessionPrincipalMismatch( f"drain by {request_principal} on session of {session.principal}" ) out, session.queue = session.queue, [] return out ```