# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-streamable-session-resume-has-silently-replayed-a-tool-call-across-an-authorization-scope-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-streamable-session-resume-has-silently-replayed-a-tool-call-across-an-authorization-scope-boundary.warrant.json
# Markdown SHA-256:   4aa192c35f54d9c6cbb7aac7a341c6ddcaa02c75c6721481504f9cbadce8dc0a
# Code AST SHA-256:   e1a4e631667296b08884264c6dc2058f6efaf8b7382bcc5c6a34fa5ddaf27222
# Verified Classes:   ScopeBoundaryReplayError, ScopeEnvelope, StreamEvent, Session
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Optional, Set


class ScopeBoundaryReplayError(RuntimeError):
    """Raised when a replayed SSE event carries a tool result whose
    originating call was authorized under a scope envelope that no longer
    matches the session's current envelope."""


@dataclass
class ScopeEnvelope:
    scopes: Set[str]
    epoch: str  # stable hash of the sorted scope set

    @classmethod
    def from_scopes(cls, scopes: Set[str]) -> "ScopeEnvelope":
        material = ",".join(sorted(scopes)).encode()
        return cls(scopes=frozenset(scopes), epoch=hashlib.sha256(material).hexdigest()[:16])


@dataclass
class StreamEvent:
    sse_id: int
    rpc_id: str
    tool: str
    required_scope: str
    payload: str
    emitted_under_epoch: str
    replayed: bool = False


@dataclass
class Session:
    session_id: str
    envelope: ScopeEnvelope
    pending: Dict[str, str] = field(default_factory=dict)  # rpc_id -> tool
    admitted_events: Dict[int, str] = field(default_factory=dict)  # sse_id -> epoch


def resume_and_deliver(
    session: Session,
    replayed_events: list[StreamEvent],
    tool_scope_map: Dict[str, str],
) -> list[StreamEvent]:
    """Adjudicate replayed events against the *current* envelope before
    admitting their payloads. Control semantics always advance; payload
    semantics are gated.
    """
    delivered: list[StreamEvent] = []

    for ev in replayed_events:
        # 1. Scope-bound session invariant: a replayed event whose epoch
        #    differs from the current envelope means the buffer outlived
        #    the credential that wrote it. Hard stop.
        if ev.replayed and ev.emitted_under_epoch != session.envelope.epoch:
            raise ScopeBoundaryReplayError(
                f"replayed sse_id={ev.sse_id} rpc_id={ev.rpc_id} tool={ev.tool!r} "
                f"emitted_under_epoch={ev.emitted_under_epoch} "
                f"current_epoch={session.envelope.epoch}; "
                "refusing to deliver payload across scope boundary"
            )

        # 2. Delivery-time re-authorization: even within the same epoch,
        #    confirm the tool's required scope is present *now*.
        required = tool_scope_map.get(ev.tool)
        if required is None or required not in session.envelope.scopes:
            raise ScopeBoundaryReplayError(
                f"tool={ev.tool!r} requires scope={required!r} not in current "
                f"envelope {sorted(session.envelope.scopes)}; "
                f"rpc_id={ev.rpc_id} cannot be resolved under present authority"
            )

        # 3. Resolve the pending call only after both checks pass.
        if ev.rpc_id not in session.pending:
            raise ScopeBoundaryReplayError(
                f"rpc_id={ev.rpc_id} not pending; replayed event has no live claim"
            )
        del session.pending[ev.rpc_id]
        session.admitted_events[ev.sse_id] = session.envelope.epoch
        delivered.append(ev)

    return delivered


def rotate_scope(session: Session, new_scopes: Set[str], buffer: Dict[int, StreamEvent]) -> None:
    """On rotation, purge buffer entries written under the prior epoch so a
    later Last-Event-ID resume cannot reach them."""
    new_env = ScopeEnvelope.from_scopes(new_scopes)
    stale = [sid for sid, ev in buffer.items() if ev.emitted_under_epoch != new_env.epoch]
    for sid in stale:
        del buffer[sid]
    session.envelope = new_env
    # Force a new session id so any in-flight resume with the old id 404s.
    session.session_id = f"{session.session_id.split('#')[0]}#{new_env.epoch}"


if __name__ == "__main__":
    old = ScopeEnvelope.from_scopes({"fs:read", "secrets:admin"})
    sess = Session(session_id="sess-7", envelope=old, pending={"c-41": "secrets.rotate"})

    stale_event = StreamEvent(
        sse_id=1180, rpc_id="c-41", tool="secrets.rotate",
        required_scope="secrets:admin", payload="ROTATED-KEY",
        emitted_under_epoch=old.epoch, replayed=True,
    )

    # Token narrowed mid-session; buffer not yet purged.
    sess.envelope = ScopeEnvelope.from_scopes({"fs:read"})

    try:
        resume_and_deliver(sess, [stale_event], {"secrets.rotate": "secrets:admin"})
    except ScopeBoundaryReplayError as e:
        print(f"BLOCKED: {e}")
