# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-surviving-mcp-session-re-binding-across-transport-reconnects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-identity-attestation-from-surviving-mcp-session-re-binding-across-transport-reconnects.warrant.json
# Markdown SHA-256:   e2b15f461d11370804976bc0c5c8dc55753d55ec674218b154136357d47a6ff8
# Code AST SHA-256:   878bd3a434a0f18f45197982978b5e1b18a532f11b35b04140d567b07febc1ad
# Verified Classes:   AttestationBindingError, Warrant, Session, AttestationStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class AttestationBindingError(RuntimeError):
    """Raised when an MCP session cannot be lawfully bound to an identity warrant."""
    pass


@dataclass
class Warrant:
    agent: str
    session_id: str
    tools: frozenset
    exp: float


@dataclass
class Session:
    id: str
    transport_principal: str  # e.g. mTLS CN; survives reconnect, NOT sufficient alone


class AttestationStore:
    """Authoritative store keyed ONLY by session id. No agent-name index on the auth path."""

    def __init__(self) -> None:
        self._by_session: Dict[str, Warrant] = {}

    def bind(self, w: Warrant) -> None:
        if w.exp <= time.time():
            raise AttestationBindingError(
                f"refusing to bind already-expired warrant for {w.agent} on {w.session_id}"
            )
        self._by_session[w.session_id] = w

    def reap(self, session_id: str) -> None:
        self._by_session.pop(session_id, None)

    def authorize(self, session: Session, tool: str) -> Warrant:
        w = self._by_session.get(session.id)
        if w is None:
            # No fallback by agent name. Force re-attestation on the new session.
            raise AttestationBindingError(
                f"no attestation bound to session {session.id} "
                f"(principal={session.transport_principal}); re-attestation required"
            )
        if w.session_id != session.id:
            # Defensive: catches any future secondary-index bug.
            raise AttestationBindingError(
                f"warrant bound to {w.session_id} presented on {session.id}"
            )
        if time.time() > w.exp:
            self.reap(session.id)
            raise AttestationBindingError(
                f"warrant for {w.agent} on {session.id} expired at {w.exp}"
            )
        if tool not in w.tools:
            raise AttestationBindingError(
                f"{w.agent} not attested for tool {tool} on {session.id}"
            )
        return w


def handle_reconnect(old_session: Session, new_session: Session, store: AttestationStore) -> None:
    """Transport reconnect is an identity event: drop the old binding, demand a new one."""
    store.reap(old_session.id)
    if store._by_session.get(new_session.id) is not None:
        # A reconnect must never inherit a binding minted for another session.
        raise AttestationBindingError(
            f"reconnect to {new_session.id} found a pre-existing binding; refusing"
        )
    # Caller is now obligated to present a fresh warrant before any tools/call.
