# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumable-sse-replay-from-silently-rebinding-an-mcp-session-to-a-stale-oauth-2-1-resource-audience-after-transport-upgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumable-sse-replay-from-silently-rebinding-an-mcp-session-to-a-stale-oauth-2-1-resource-audience-after-transport-upgrade.warrant.json
# Markdown SHA-256:   b96b2a1d480345d304bf72d4b562a82724ba4641e5e72a4bdabe61d5d7e80d46
# Code AST SHA-256:   1ffa6d5558addedf132713914d8ff30dd6febdfbafdb275fd502b8f4d73629a4
# Verified Classes:   AudienceRebindError, TokenContext, CursorBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AudienceRebindError(RuntimeError):
    """Raised when a resumable SSE cursor would be replayed across an
    authorization-context change (RFC 8707 resource audience mismatch)."""


@dataclass(frozen=True)
class TokenContext:
    iss: str
    aud: str
    jkt: str  # proof-of-possession thumbprint

    def fingerprint(self) -> str:
        raw = f"{self.iss}|{self.aud}|{self.jkt}".encode()
        return hashlib.sha256(raw).hexdigest()


@dataclass(frozen=True)
class CursorBinding:
    session_id: str
    last_event_id: str
    bound: TokenContext


def resume_stream(
    cursor: CursorBinding,
    presented: TokenContext,
    allowed_audiences: frozenset[str],
) -> str:
    # Membership check alone is the bug: it accepts a *different* allowed audience.
    if presented.aud not in allowed_audiences:
        raise AudienceRebindError(
            f"audience {presented.aud!r} not in allow-list {sorted(allowed_audiences)}"
        )

    # The load-bearing invariant: equality against the session's bound context,
    # not membership in the allow-list. jkt alone is insufficient; aud must match.
    if presented.fingerprint() != cursor.bound.fingerprint():
        raise AudienceRebindError(
            "resume rejected: presented token context "
            f"(aud={presented.aud!r}, jkt={presented.jkt!r}) does not equal "
            f"session binding (aud={cursor.bound.aud!r}, jkt={cursor.bound.jkt!r}); "
            "cursor invalidated, re-initialize required"
        )

    return f"replay from {cursor.last_event_id} under aud={presented.aud!r}"


# Observed failure: refresh preserved jkt but changed aud tenant-a -> umbrella.
session = CursorBinding(
    session_id="s-7f3a",
    last_event_id="evt-0412",
    bound=TokenContext(iss="https://as.example", aud="https://mcp.tenant-a.example", jkt="K1"),
)
refreshed = TokenContext(iss="https://as.example", aud="https://mcp.example", jkt="K1")

try:
    resume_stream(session, refreshed, frozenset({"https://mcp.example", "https://mcp.tenant-a.example"}))
except AudienceRebindError as exc:
    # Correct behavior: fail closed, drop cursor, force re-initialize handshake.
    print(f"blocked silent rebind: {exc}")
