# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-resumed-mcp-sse-stream-from-replaying-another-tenant-s-authorization-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-resumed-mcp-sse-stream-from-replaying-another-tenant-s-authorization-epoch.warrant.json
# Markdown SHA-256:   928acf93e98a5d3530c834b46328cfe291a067b73880f10812afb0ac190e7809
# Code AST SHA-256:   9ab4265c25f308874db8bc1ed36fa03525b03f5b61df60df441e35ee97b3330f
# Verified Classes:   EpochMismatchError, Principal, Frame, SessionBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class EpochMismatchError(RuntimeError):
    """Raised when a resume cursor does not belong to the caller's current auth epoch."""
    pass


@dataclass(frozen=True)
class Principal:
    tenant_id: str
    subject_id: str
    credential_fingerprint: str  # hash of jti / token, NOT the raw token

    def epoch(self, session_id: str) -> str:
        # Epoch is derived from the full principal binding and the session,
        # so any credential change (refresh, revocation+reissue, role change)
        # rotates it even when tenant_id is unchanged.
        h = hashlib.sha256()
        h.update(session_id.encode())
        h.update(b"\x00")
        h.update(self.tenant_id.encode())
        h.update(b"\x00")
        h.update(self.subject_id.encode())
        h.update(b"\x00")
        h.update(self.credential_fingerprint.encode())
        return h.hexdigest()[:32]


@dataclass
class Frame:
    seq: int
    epoch: str
    payload: dict


@dataclass
class SessionBuffer:
    session_id: str
    # Buffers are partitioned by epoch. A frame produced under E1 is
    # physically unreachable from a request authorized under E2.
    partitions: dict[str, list[Frame]] = field(default_factory=dict)

    def append(self, frame: Frame) -> None:
        self.partitions.setdefault(frame.epoch, []).append(frame)

    def resume(self, principal: Principal, last_event_id: int) -> list[Frame]:
        current = principal.epoch(self.session_id)
        frames = self.partitions.get(current, [])
        if not frames and last_event_id > 0:
            # Cursor predates the current epoch: the caller is asking to
            # replay frames it was not authorized to receive under its
            # present credential. Fail closed; do not fall back to a
            # shared or stale partition.
            raise EpochMismatchError(
                f"resume rejected for session={self.session_id} "
                f"epoch={current[:8]} last_event_id={last_event_id}: "
                f"cursor belongs to a prior authorization epoch"
            )
        return [f for f in frames if f.seq > last_event_id]

    def rotate_epoch(self, old_epoch: str) -> None:
        # On epoch transition, tombstone the prior partition so it cannot
        # be addressed by a cursor even if the epoch check is bypassed.
        self.partitions.pop(old_epoch, None)


def handle_resume(
    buf: SessionBuffer,
    presented_principal: Principal,
    last_event_id: int,
) -> list[Frame]:
    if last_event_id < 0:
        raise EpochMismatchError("negative Last-Event-ID is not a valid cursor")
    frames = buf.resume(presented_principal, last_event_id)
    if not frames and last_event_id > 0:
        # Empty but non-error path: caller is fully caught up under the
        # current epoch. Legitimate; return nothing.
        return []
    return frames


def demo() -> None:
    buf = SessionBuffer(session_id="sess_7f3a")
    tenant_a = Principal("tenant-a", "user-1", "fp-A")
    tenant_b = Principal("tenant-b", "user-9", "fp-B")

    buf.append(Frame(seq=1, epoch=tenant_a.epoch("sess_7f3a"),
                     payload={"tool": "get_customer", "result": "A-secret"}))
    buf.append(Frame(seq=2, epoch=tenant_a.epoch("sess_7f3a"),
                     payload={"sampling": "A-context"}))

    # Tenant B presents a valid token and the leaked session id.
    try:
        handle_resume(buf, tenant_b, last_event_id=1)
    except EpochMismatchError as e:
        print("blocked:", e)

    # Correct path: tenant A resumes its own stream.
    ok = handle_resume(buf, tenant_a, last_event_id=1)
    assert [f.seq for f in ok] == [2]


if __name__ == "__main__":
    demo()
