Which invariants prevent SSE resumption from re-binding a stale MCP session to a rotated OAuth 2.1 resource token

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers using the Streamable HTTP transport (JSON-RPC over POST + optional GET SSE stream, `Mcp-Session-Id` header, `Last-Event-ID` resumption) fronted by an OAuth 2.1 resource server that validates bearer tokens with short TTLs. Does not cover stdio transport, nor servers that pin a single static token per process lifetime.

Core Distinction

There are two independent identity axes on a Streamable HTTP MCP connection, and they are *not* the same axis:

  1. **Session identity** — the opaque `Mcp-Session-Id` minted at `initialize`, which scopes server-side state (tool registry view, subscriptions, in-flight SSE event log keyed by `Last-Event-ID`).
  2. **Authorization identity** — the OAuth 2.1 access token presented on each HTTP request, validated by the resource server against an audience-bound, short-TTL credential with scopes.

The transport spec treats the session ID as a bearer-ish handle for *resumption*: a client that lost its SSE stream reconnects with `GET` + `Last-Event-ID` + `Mcp-Session-Id` and expects the server to replay buffered events from that cursor. The failure mode is that **resumption is authorized only by "the request carried *a* valid token," not by "the request carried a token whose subject/scope matches the principal that owned this session at event-emission time."** When the token rotates (expiry + refresh, or a re-`initialize` under a new grant), the session ID survives but the authorization context underneath it has changed. The server happily replays events that were generated under the old principal's scopes into a stream now authorized by a different (often narrower) principal — or worse, accepts a resumption under a *broader* token and exposes buffered tool results the original grant never covered.

What Was Observed

A multi-tenant MCP server exposed a `search_documents` tool and a long-running `subscribe_changes` SSE stream. The client flow:

  1. `POST /mcp initialize` with access token `T1` (scope `docs:read`, `sub=alice`, `exp=+300s`). Server returns `Mcp-Session-Id: S1` and binds `S1 → {sub: alice, scopes: [docs:read]}`.
  2. Client opens `GET /mcp` with `Mcp-Session-Id: S1`, token `T1`. Server streams events `id: 1001`, `id: 1002`, … Server buffers events in a per-session ring buffer keyed by `Last-Event-ID`.
  3. At t+300s, `T1` expires. The SSE connection drops (network blip / proxy idle timeout).
  4. Client refreshes to `T2`. Crucially, in this incident the refresh was performed by a *different* OAuth client instance that had been granted `docs:read docs:write admin:audit` for the same `sub=alice` — a step-up token minted for an admin console. The client library reused the persisted `Mcp-Session-Id: S1`.
  5. Client resumes: `GET /mcp` with `Mcp-Session-Id: S1`, `Last-Event-ID: 1002`, `Authorization: Bearer T2`.
  6. Server validates `T2` (valid, correct audience, `sub=alice`), looks up `S1`, finds the buffer, and replays events `1003…1050`. Several of those events were notifications emitted while `S1` was created under `T1`'s scope set — specifically, a `notifications/message` carrying a document body that had been fetched under `docs:read` but was **redacted at emission time for the `docs:read`-only principal** and stored unredacted in the buffer because the redaction was applied at *stream-write* time, not *buffer-write* time.

The client received unredacted bodies it should not have seen under the original grant, and the audit log recorded the replay under `T2`'s identity, so the leak was invisible in per-token audit correlation.

The root cause is not "token rotation." It is that **the session's authorization binding was evaluated once at `initialize` and never re-evaluated at resumption**, while the event buffer stored pre-redaction payloads.

Condition of Validity

The guardrail holds — i.e., resumption is safe — only when *all* of the following are true simultaneously:

The invariant is therefore: **for every byte replayed on resumption, `scopes(resumption_token) ⊇ scopes(event_emission_token)` and `sub(resumption_token) == sub(event_emission_token)`.** If you cannot prove this from stored metadata, you cannot safely replay.

Decision Boundary

The boundary is not "expired vs. valid token." It is **"same grant vs. different grant under same subject."** Three regimes:

The non-obvious part: a *narrower* resumption token is the dangerous one, because the naive "is the token valid?" check passes and the buffer was written assuming the broader emission context. Most implementations guard the "broader token" direction (privilege escalation) and miss the "narrower token replaying broader-context events" direction, which is the actual data-exposure vector.

Operational Effect

Without the invariant, the following concrete effects occur:

The mitigation is structural: bind the session to `(sub, grant_id)` at `initialize`, store per-event authorization snapshots, redact at buffer-write, and enforce the superset check on every resumption. Treat `Last-Event-ID` replay as a *re-authorization* event, not a cache hit.

from dataclasses import dataclass
from typing import Optional


class ResumptionAuthorizationError(RuntimeError):
    """Raised when an SSE resumption request cannot be safely authorized
    against the authorization context that was in force when the buffered
    events were emitted."""


@dataclass(frozen=True)
class AuthContext:
    sub: str
    grant_id: str
    scopes: frozenset[str]

    def covers(self, other: "AuthContext") -> bool:
        # A resumption context covers an emission context iff same subject,
        # same grant lineage, and every emission scope is present.
        return (
            self.sub == other.sub
            and self.grant_id == other.grant_id
            and other.scopes.issubset(self.scopes)
        )


@dataclass(frozen=True)
class BufferedEvent:
    event_id: int
    payload: str  # already redacted at buffer-write time
    emission_ctx: AuthContext


def authorize_resumption(
    session_sub: str,
    session_grant_id: str,
    resumption_ctx: AuthContext,
    buffer: list[BufferedEvent],
    last_event_id: Optional[int],
) -> list[BufferedEvent]:
    # Invariant 1: session is bound to the subject that minted it.
    if resumption_ctx.sub != session_sub:
        raise ResumptionAuthorizationError(
            f"session bound to sub={session_sub!r}, "
            f"resumption token sub={resumption_ctx.sub!r}"
        )
    # Invariant 2: same grant lineage; a re-initialize under a new grant
    # must mint a new session, not reuse this one.
    if resumption_ctx.grant_id != session_grant_id:
        raise ResumptionAuthorizationError(
            f"session grant_id={session_grant_id!r} does not match "
            f"resumption grant_id={resumption_ctx.grant_id!r}; "
            f"re-initialize required"
        )

    start = 0 if last_event_id is None else None
    replay: list[BufferedEvent] = []
    for ev in buffer:
        if last_event_id is not None and ev.event_id <= last_event_id:
            continue
        # Invariant 3: resumption context must cover every emission context
        # in the replay range. A narrower token must not replay broader events.
        if not resumption_ctx.covers(ev.emission_ctx):
            raise ResumptionAuthorizationError(
                f"event {ev.event_id} emitted under scopes "
                f"{sorted(ev.emission_ctx.scopes)} not covered by "
                f"resumption scopes {sorted(resumption_ctx.scopes)}"
            )
        replay.append(ev)

    if start is not None and not replay:
        # No cursor and empty buffer: nothing to replay, caller proceeds.
        return replay
    return replay


def handle_get_resume(
    session_sub: str,
    session_grant_id: str,
    resumption_ctx: AuthContext,
    buffer: list[BufferedEvent],
    last_event_id: Optional[int],
) -> list[BufferedEvent]:
    try:
        return authorize_resumption(
            session_sub, session_grant_id, resumption_ctx, buffer, last_event_id
        )
    except ResumptionAuthorizationError:
        # Do NOT fall back to "replay anyway" or "replay with redaction."
        # A failed coverage check means the buffer may contain payloads the
        # resumption principal is not entitled to; force re-initialize.
        raise