# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-oauth-resource-binding-after-a-resumable-sse-replay-and-why-does-the-resume-token-silently-outlive-its-authoriz.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-oauth-resource-binding-after-a-resumable-sse-replay-and-why-does-the-resume-token-silently-outlive-its-authoriz.warrant.json
# Markdown SHA-256:   ac66574c3497dfc5bad7239f2a2770d586e2dfca6ed79f94fe59a763eeb8ac3b
# Code AST SHA-256:   7aae65834a157cb7074e9ab72d78aed465ec8368b3b068b22bcfd57ff8991c81
# Verified Classes:   ResumeContextMismatch, AuthContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from hashlib import sha256
from typing import FrozenSet


class ResumeContextMismatch(RuntimeError):
    """Raised when an SSE resume cursor is presented under a different
    authorization context than the one that opened the stream."""


@dataclass(frozen=True)
class AuthContext:
    aud: str
    sub: str
    client_id: str
    scopes: FrozenSet[str]

    def fingerprint(self) -> str:
        material = "|".join([
            self.aud,
            self.sub,
            self.client_id,
            ",".join(sorted(self.scopes)),
        ])
        return sha256(material.encode("utf-8")).hexdigest()


def admit_resume(
    opening: AuthContext,
    resuming: AuthContext,
    last_event_id: str,
) -> None:
    # Audience and subject are hard identity: a different resource server
    # or a different principal must never replay another stream's events.
    if resuming.aud != opening.aud:
        raise ResumeContextMismatch(
            f"aud mismatch on resume of {last_event_id}: "
            f"opened={opening.aud!r} resumed={resuming.aud!r}"
        )
    if resuming.sub != opening.sub:
        raise ResumeContextMismatch(
            f"sub mismatch on resume of {last_event_id}: "
            f"opened={opening.sub!r} resumed={resuming.sub!r}"
        )
    # A different client resuming another client's stream is session fixation.
    if resuming.client_id != opening.client_id:
        raise ResumeContextMismatch(
            f"client_id mismatch on resume of {last_event_id}: "
            f"opened={opening.client_id!r} resumed={resuming.client_id!r}"
        )
    # Scope narrowing on refresh is the common case; it must fail closed
    # because replayed events were produced under the wider grant.
    if not opening.scopes.issubset(resuming.scopes):
        narrowed = sorted(opening.scopes - resuming.scopes)
        raise ResumeContextMismatch(
            f"scope narrowing on resume of {last_event_id}: "
            f"lost={narrowed} (replayed events were produced under wider grant)"
        )


def handle_sse_resume(
    opening_ctx: AuthContext,
    presented_ctx: AuthContext,
    last_event_id: str,
) -> str:
    try:
        admit_resume(opening_ctx, presented_ctx, last_event_id)
    except ResumeContextMismatch:
        # Fail closed: no partial replay. Force a clean re-initialization.
        raise
    return f"resume-ok:{last_event_id}"
