# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-oauth-2-1-resource-indicator-mismatch-across-mcp-streamable-http-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-oauth-2-1-resource-indicator-mismatch-across-mcp-streamable-http-session-resumption.warrant.json
# Markdown SHA-256:   98e0a1a137fec10c428b13f4f0456e39b3454ea5fc73822916f924c74eb002c5
# Code AST SHA-256:   1921698aeaa5eb2b4c327c0f58109fb43b343014441f7fd3868e513f310ec1c2
# Verified Classes:   ResourceIndicatorMismatch, Session, AccessToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResourceIndicatorMismatch(RuntimeError):
    """Raised when a resumed MCP session's bound resource disagrees with the presented token's audience."""
    pass


@dataclass(frozen=True)
class Session:
    session_id: str
    bound_resource: str          # resource indicator the session was authorized against
    last_event_id: int
    principal: str               # cached authorization context, keyed by session


@dataclass(frozen=True)
class AccessToken:
    aud: str                     # RFC 8707 resource indicator, may be normalized by an AS proxy
    scope: frozenset[str]
    exp: int


def resume_session(
    session: Session,
    token: AccessToken,
    presented_last_event_id: int,
    now: int,
    required_scope: str = "mcp:tools",
) -> Session:
    if token.exp <= now:
        raise ResourceIndicatorMismatch(
            f"token expired at {token.exp}, resume attempted at {now}"
        )
    if required_scope not in token.scope:
        raise ResourceIndicatorMismatch(
            f"token scope {sorted(token.scope)} lacks required '{required_scope}'"
        )
    # The invariant the transport does not enforce: the token must be
    # authorized for the exact resource the session was bound to. A
    # normalization difference (trailing path, scheme case, port) is
    # still a mismatch — the session principal was derived under the
    # original indicator and replayed events inherit that authority.
    if token.aud != session.bound_resource:
        raise ResourceIndicatorMismatch(
            "session resume rejected: token aud "
            f"{token.aud!r} != session bound_resource {session.bound_resource!r} "
            f"(session {session.session_id}, cursor {presented_last_event_id}); "
            "replayed events would carry authority the presented token does not hold"
        )
    if presented_last_event_id > session.last_event_id:
        raise ResourceIndicatorMismatch(
            f"cursor {presented_last_event_id} ahead of session head {session.last_event_id}"
        )
    return Session(
        session_id=session.session_id,
        bound_resource=session.bound_resource,
        last_event_id=presented_last_event_id,
        principal=session.principal,
    )
