# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-silent-warrant-loss-during-mcp-resumable-sse-to-streamable-http-migration-under-oauth-2-1-resource-server-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-silent-warrant-loss-during-mcp-resumable-sse-to-streamable-http-migration-under-oauth-2-1-resource-server-binding.warrant.json
# Markdown SHA-256:   8beef6ba0b8d7ffaaed0ca7e5879b43e7c93ad9747d01b5e2ebb019ef123a35e
# Code AST SHA-256:   126efe635d0208c0e00aab476ea5e14d6e4e6bdf6205947058a786fd94bead87
# Verified Classes:   WarrantBindingError, SessionNotFoundError, Warrant, SessionRecord, McpSessionStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class WarrantBindingError(RuntimeError):
    """Raised when a session resumption presents a warrant that does not match the session's origin warrant."""
    pass


class SessionNotFoundError(RuntimeError):
    pass


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

    def fingerprint(self) -> str:
        material = f"{self.sub}|{','.join(sorted(self.scope))}|{self.aud}"
        return hashlib.sha256(material.encode()).hexdigest()


@dataclass
class SessionRecord:
    session_id: str
    origin_warrant: Warrant
    capabilities_snapshot: frozenset[str]
    replay_buffer: list[str] = field(default_factory=list)


class McpSessionStore:
    def __init__(self) -> None:
        self._sessions: dict[str, SessionRecord] = {}

    def initialize(self, session_id: str, warrant: Warrant, capabilities: frozenset[str]) -> SessionRecord:
        rec = SessionRecord(session_id=session_id, origin_warrant=warrant, capabilities_snapshot=capabilities)
        self._sessions[session_id] = rec
        return rec

    def resume(self, session_id: str, presented: Warrant, last_event_id: Optional[str]) -> SessionRecord:
        rec = self._sessions.get(session_id)
        if rec is None:
            raise SessionNotFoundError(f"no session {session_id}")

        origin = rec.origin_warrant

        # Hard precondition: subject binding. Audience match must NOT short-circuit this.
        if presented.aud != origin.aud:
            self._sessions.pop(session_id, None)
            raise WarrantBindingError(
                f"audience mismatch on resume of {session_id}: origin={origin.aud} presented={presented.aud}"
            )
        if presented.sub != origin.sub:
            # Cross-principal resumption: invalidate the session entirely to block replay by origin token.
            self._sessions.pop(session_id, None)
            raise WarrantBindingError(
                f"subject mismatch on resume of {session_id}: origin={origin.sub} presented={presented.sub}; session invalidated"
            )

        # Scope superset check: resuming warrant must not be narrower than capabilities granted at init.
        if not rec.capabilities_snapshot.issubset(presented.scope):
            self._sessions.pop(session_id, None)
            raise WarrantBindingError(
                f"scope regression on resume of {session_id}: capabilities={sorted(rec.capabilities_snapshot)} presented={sorted(presented.scope)}"
            )

        # Replay cursor is warrant-scoped: only honor Last-Event-ID if the fingerprint matches.
        if last_event_id is not None and presented.fingerprint() != origin.fingerprint():
            raise WarrantBindingError(
                f"Last-Event-ID {last_event_id} presented under warrant fingerprint {presented.fingerprint()} "
                f"but session {session_id} was initialized under {origin.fingerprint()}"
            )

        return rec


def handle_streamable_http_request(store: McpSessionStore, session_id: str, bearer: Warrant, last_event_id: Optional[str]) -> SessionRecord:
    try:
        return store.resume(session_id, bearer, last_event_id)
    except WarrantBindingError as e:
        # Fail closed: surface as 403 to the client, do not fall through to a fresh session silently.
        raise WarrantBindingError(f"refusing resumption: {e}") from e
