# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumed-mcp-streamable-http-session-when-the-oauth-2-1-token-s-resource-binding-no-longer-matches-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-resumed-mcp-streamable-http-session-when-the-oauth-2-1-token-s-resource-binding-no-longer-matches-the.warrant.json
# Markdown SHA-256:   25a2bbded9c037c35f27eda3c277efd5d182da3d58fe0caf0d1d28b2775b4598
# Code AST SHA-256:   d6eec5ccf64c4463b7b0ecd6f1c327edf9799c043c34bd5434b8b9435c7600a6
# Verified Classes:   ResourceBindingMismatch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResourceBindingMismatch(RuntimeError):
    """Raised when a resumed MCP session's stored resource indicator
    does not match the bearer token's RFC 8707 `resource` claim."""
    pass


def resume_session(
    session_id: str,
    last_event_id: str | None,
    token_resource: str,
    request_resource: str,
    session_store: dict,
) -> dict:
    """Gate streamable-HTTP session resumption on resource-binding equality.

    Returns the session record only if the invariant holds; otherwise raises
    before any replayed event is emitted.
    """
    session = session_store.get(session_id)
    if session is None:
        raise ResourceBindingMismatch(
            f"unknown session {session_id!r}; refusing resume"
        )

    stored = session.get("resource_indicator")
    if stored is None:
        # Pre-invariant session: cannot prove binding, fail closed.
        raise ResourceBindingMismatch(
            f"session {session_id!r} has no recorded resource_indicator; "
            "unresumable, client must start a new session"
        )

    # Primary invariant: token must match the binding at creation time.
    if stored != token_resource:
        raise ResourceBindingMismatch(
            f"session {session_id!r} bound to {stored!r}, "
            f"token bound to {token_resource!r}; "
            "re-authorize against original resource or abandon session"
        )

    # Secondary invariant: live request must also target the bound resource.
    if stored != request_resource:
        raise ResourceBindingMismatch(
            f"session {session_id!r} bound to {stored!r}, "
            f"request targets {request_resource!r}; "
            "edge/origin change requires explicit re-scoping, not silent resume"
        )

    # Only now is Last-Event-ID replay safe to honor.
    session["resume_from"] = last_event_id
    return session
