# Which invariants prevent a resumed MCP SSE stream from replaying another tenant's authorization epoch **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing HTTP-native transports (Streamable HTTP / SSE) with `Last-Event-ID` resumption and per-tenant bearer/token authorization. Does not apply to stdio transports, nor to stateless single-tenant SSE proxies that terminate and re-establish the entire stream on reconnect. ## Core Distinction The failure is not "a token expired mid-stream." It is the collision of two independent monotonic sequences that the MCP transport layer treats as one: 1. **The event sequence** — a per-session, monotonically increasing `id:` counter that the client echoes back as `Last-Event-ID` to resume. 2. **The authorization epoch** — the tenant/credential binding under which the session was opened, which can change (token refresh, tenant re-scoping, role downgrade, revocation) without the event sequence resetting. HTTP-native MCP resumption is defined only over (1). Nothing in the transport contract requires the server to re-validate that the credential presented on the *resume* request is the same principal that was authorized to receive events at position `N`. A resume request is therefore an *unauthenticated index into a prior authorization context* unless the server explicitly binds the two. When a multi-tenant server keeps a replayable event buffer keyed only by `session_id` + `Last-Event-ID`, a client that presents a valid token for tenant B can resume a stream whose buffered events were produced under tenant A — and the server will faithfully replay tool-call results, resource bodies, and sampling payloads across the tenant boundary. The invariant that is missing by default: **the resume cursor must be a function of (session, epoch), not (session) alone.** ## What Was Observed A gateway multiplexing MCP Streamable HTTP for ~40 tenants held per-session ring buffers of the last 256 SSE frames to support `Last-Event-ID` replay after mobile-network drops. Sessions were keyed `sess_`; buffers were `dict[str, deque[Frame]]`. Authorization was enforced at *stream open*: the `Authorization` header was validated, `tenant_id` extracted, and the session record annotated with the tenant. The replay path looked correct in isolation: ``` GET /mcp/session/sess_7f3a Last-Event-ID: 1188 Authorization: Bearer ``` The handler validated the token (tenant B), looked up `sess_7f3a`, found the buffer, and replayed frames `1189..1204`. Frames `1189..1204` had been generated while `sess_7f3a` was bound to tenant A — they contained a `tools/call` result returning tenant A's `customer_record` resource and a `sampling/createMessage` response. Tenant B received them. The token check passed; the session check passed; the *correlation* between them was never checked. The trigger condition is narrow and easy to reproduce: - A session is opened and authorized under tenant A. - The client disconnects (network drop, tab close, agent restart) — the server retains the buffer for a TTL (here, 300s) to allow resumption. - A second client, or the same client after a tenant switch / re-auth flow, presents a *valid* token for tenant B but the *same* `session_id` (leaked via logs, a shared browser profile, an agent that reuses a session handle across sub-tasks, or a server that issues session IDs before auth completes). - The resume succeeds and replays cross-tenant frames. This is not prompt injection and not a sandbox escape. The LLM correctly reasons over the frames it is given; the *transport* handed it another tenant's state. The agent then treats foreign tool output as its own episodic memory — a state-continuity poisoning that no amount of in-context reasoning can detect, because the frames are structurally indistinguishable from legitimate ones. ## Condition of Validity The guardrail is only valid under three conjoined conditions. Break any one and the replay window reopens: 1. **Epoch is part of the cursor.** The `Last-Event-ID` namespace must be scoped to `(session_id, auth_epoch)`, where `auth_epoch` is a server-generated opaque value issued at stream open and bound to the exact principal (tenant + subject + credential `jti` or hash). Resume requests must present the epoch; the server rejects any cursor whose epoch does not match the currently authorized principal. The epoch must be **rotated on every credential change**, not merely on re-login. 2. **Buffers are not shared across epochs.** A frame produced under epoch `E1` must be physically unreachable from a request authorized under `E2`. Implementations that "check the epoch but replay from a shared deque" still leak on off-by-one windows and on concurrent append during replay. The buffer must be partitioned by epoch, and epoch transition must *drain or tombstone* the old partition rather than leaving it addressable. 3. **Session IDs are not bearer secrets.** If a `session_id` alone (plus any valid token) grants resume, then session IDs are credentials and must be treated as such: high-entropy, never logged, rotated with the epoch, and never reused across principals. The common shortcut — `session_id = hash(tenant_id)` or a short counter — makes cross-tenant resume a matter of guessing, not leaking. A subtly insufficient variant worth naming: servers that re-run the *same* authorization middleware on resume and compare `tenant_id` to the session record. This catches tenant A → tenant B, but misses **same-tenant, different-subject** escalation (a sub-agent under the same tenant but a narrower role resuming a broader stream) and **same-subject, revoked-then-reissued** tokens, because `tenant_id` is unchanged across the epoch boundary. The comparison must be over the full principal binding, not the tenant label. ## Decision Boundary The boundary is between **resumption as a transport convenience** and **resumption as an authorization decision**. They coincide only when the replay set is provably a subset of what the resuming principal is entitled to read *now*. Operationally: - If the server can prove `replay_set ⊆ authorized_read_set(current_principal)` — e.g., because buffers are per-epoch and the epoch is bound to the current principal — resume is a pure transport operation and may proceed without re-evaluation. - If it cannot, resume is an authorization event and must be treated as a *new* stream open: re-validate the principal, re-derive the authorized read set, and **drop any cursor that predates the current epoch** rather than silently replaying from a stale partition. The failure mode lives precisely in the gap where the server believes it is in case 1 but is actually in case 2. The most common cause of that misbelief is a buffer keyed by `session_id` while the authorization check keys by token — two keys that were coincidentally equal at stream open and diverge on every subsequent event. There is a tempting-but-wrong resolution: "just replay everything and let the client filter by tenant." This pushes the invariant into the untrusted client and into the probabilistic reasoning layer, where an LLM agent has no reliable way to distinguish foreign frames from its own prior state. The invariant must hold server-side and pre-replay. ## Operational Effect When the invariant holds, the observable behavior is that a resume under a changed epoch **fails closed with a resumable error**: the server returns `409 Conflict` (or an MCP-level error carrying `resume_rejected: epoch_mismatch`) and instructs the client to re-open the stream from position 0 under the new epoch. The client's in-flight tool call is re-issued; the agent's context is rebuilt from a clean, correctly-scoped replay. Cost: one extra round trip and a re-execution of any non-idempotent tool call whose result was in the dropped window — which is why tool calls inside resumable streams should carry idempotency keys, so re-execution collapses to a cached result rather than a duplicate side effect. When it does not hold, the observable behavior is silent and delayed: the agent proceeds with a context that contains another principal's tool outputs, and the corruption surfaces only later as a hallucinated cross-tenant reference, a leaked resource body in a downstream summary, or an auditor replay that cannot reconcile the agent's stated inputs with the server's event log. The corruption is *not* detectable from the agent's perspective, which is what makes it an operational invariant rather than a bug to be caught in review. The practical consequence for agent operators: any MCP client that reuses `session_id` across credential changes, tenant switches, or sub-agent handoffs is a latent cross-tenant replay vector, and any MCP server that stores replay buffers keyed by session alone is the exploit. Both sides must carry the epoch; neither alone is sufficient. ```python import hashlib import time from dataclasses import dataclass, field from typing import Optional class EpochMismatchError(RuntimeError): """Raised when a resume cursor does not belong to the caller's current auth epoch.""" pass @dataclass(frozen=True) class Principal: tenant_id: str subject_id: str credential_fingerprint: str # hash of jti / token, NOT the raw token def epoch(self, session_id: str) -> str: # Epoch is derived from the full principal binding and the session, # so any credential change (refresh, revocation+reissue, role change) # rotates it even when tenant_id is unchanged. h = hashlib.sha256() h.update(session_id.encode()) h.update(b"\x00") h.update(self.tenant_id.encode()) h.update(b"\x00") h.update(self.subject_id.encode()) h.update(b"\x00") h.update(self.credential_fingerprint.encode()) return h.hexdigest()[:32] @dataclass class Frame: seq: int epoch: str payload: dict @dataclass class SessionBuffer: session_id: str # Buffers are partitioned by epoch. A frame produced under E1 is # physically unreachable from a request authorized under E2. partitions: dict[str, list[Frame]] = field(default_factory=dict) def append(self, frame: Frame) -> None: self.partitions.setdefault(frame.epoch, []).append(frame) def resume(self, principal: Principal, last_event_id: int) -> list[Frame]: current = principal.epoch(self.session_id) frames = self.partitions.get(current, []) if not frames and last_event_id > 0: # Cursor predates the current epoch: the caller is asking to # replay frames it was not authorized to receive under its # present credential. Fail closed; do not fall back to a # shared or stale partition. raise EpochMismatchError( f"resume rejected for session={self.session_id} " f"epoch={current[:8]} last_event_id={last_event_id}: " f"cursor belongs to a prior authorization epoch" ) return [f for f in frames if f.seq > last_event_id] def rotate_epoch(self, old_epoch: str) -> None: # On epoch transition, tombstone the prior partition so it cannot # be addressed by a cursor even if the epoch check is bypassed. self.partitions.pop(old_epoch, None) def handle_resume( buf: SessionBuffer, presented_principal: Principal, last_event_id: int, ) -> list[Frame]: if last_event_id < 0: raise EpochMismatchError("negative Last-Event-ID is not a valid cursor") frames = buf.resume(presented_principal, last_event_id) if not frames and last_event_id > 0: # Empty but non-error path: caller is fully caught up under the # current epoch. Legitimate; return nothing. return [] return frames def demo() -> None: buf = SessionBuffer(session_id="sess_7f3a") tenant_a = Principal("tenant-a", "user-1", "fp-A") tenant_b = Principal("tenant-b", "user-9", "fp-B") buf.append(Frame(seq=1, epoch=tenant_a.epoch("sess_7f3a"), payload={"tool": "get_customer", "result": "A-secret"})) buf.append(Frame(seq=2, epoch=tenant_a.epoch("sess_7f3a"), payload={"sampling": "A-context"})) # Tenant B presents a valid token and the leaked session id. try: handle_resume(buf, tenant_b, last_event_id=1) except EpochMismatchError as e: print("blocked:", e) # Correct path: tenant A resumes its own stream. ok = handle_resume(buf, tenant_a, last_event_id=1) assert [f.seq for f in ok] == [2] if __name__ == "__main__": demo() ```