# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-sse-session-after-the-oauth-2-1-access-token-that-bound-the-session-has-been-rotated.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-sse-session-after-the-oauth-2-1-access-token-that-bound-the-session-has-been-rotated.warrant.json
# Markdown SHA-256:   d26903868f0b4bd15caefe4c38d8d6589791f43748e2380fba881c92146f5b03
# Code AST SHA-256:   6adec9ff2276aea93c21a886cd5ea63ab182c6d559b6e89ac1e2d346e771350c
# Verified Classes:   SessionAuthorizationMismatch, TokenContext, SessionRecord
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SessionAuthorizationMismatch(RuntimeError):
    """Raised when a resume request presents a token whose authorization
    context is not a superset of the context recorded at session creation."""
    pass


@dataclass(frozen=True)
class TokenContext:
    sub: str
    aud: str
    scopes: frozenset[str]
    jti: str


@dataclass
class SessionRecord:
    session_id: str
    created_by: TokenContext
    buffered_event_ids: list[str] = field(default_factory=list)
    # per-event grant tag: event_id -> scope set under which it was produced
    event_grants: dict[str, frozenset[str]] = field(default_factory=dict)


def resume_session(
    record: SessionRecord,
    presenting: TokenContext,
    last_event_id: Optional[str],
) -> list[str]:
    """Return the event IDs safe to replay to `presenting`.

    Enforces the session-authorization invariant: the presenting token must
    share sub and aud with the session creator, and its scopes must be a
    superset of the creator's scopes. Otherwise the resume is rejected
    rather than silently leaking broader-scoped historical events.
    """
    if presenting.sub != record.created_by.sub:
        raise SessionAuthorizationMismatch(
            f"subject mismatch on resume: session={record.session_id} "
            f"created_by={record.created_by.sub!r} presenting={presenting.sub!r}"
        )
    if presenting.aud != record.created_by.aud:
        raise SessionAuthorizationMismatch(
            f"audience mismatch on resume: session={record.session_id} "
            f"expected_aud={record.created_by.aud!r} presenting_aud={presenting.aud!r}"
        )
    missing = record.created_by.scopes - presenting.scopes
    if missing:
        # Downgraded token: replaying the buffer would leak events produced
        # under scopes the presenter no longer holds.
        raise SessionAuthorizationMismatch(
            f"scope downgrade on resume: session={record.session_id} "
            f"missing_scopes={sorted(missing)}"
        )

    if last_event_id is None:
        return list(record.buffered_event_ids)

    if last_event_id not in record.event_grants:
        # Unknown cursor: refuse rather than replay from the start, because
        # a start-of-buffer replay re-delivers every historical event.
        raise SessionAuthorizationMismatch(
            f"unknown Last-Event-ID {last_event_id!r} for session {record.session_id}"
        )

    idx = record.buffered_event_ids.index(last_event_id)
    replay = record.buffered_event_ids[idx + 1:]

    # Defense in depth: even with a superset token, never replay an event
    # whose recorded grant exceeds the presenter's current scopes.
    for eid in replay:
        grant = record.event_grants.get(eid, frozenset())
        if not grant <= presenting.scopes:
            raise SessionAuthorizationMismatch(
                f"event {eid!r} was produced under scopes {sorted(grant)} "
                f"not held by presenter {sorted(presenting.scopes)}"
            )
    return replay
