# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-mcp-session-identity-has-silently-outlived-the-client-certificate-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-mcp-session-identity-has-silently-outlived-the-client-certificate-that-authorized-it.warrant.json
# Markdown SHA-256:   f44b2b78956acad4e6b0070d6a36e0402a3cc7042d08ba263bf77bf81cc25dcb
# Code AST SHA-256:   8467a4c2ec0a24152d2061407350097a84f2e0d800138abe278be5706ed20239
# Verified Classes:   AuthorityLapseError, CertBinding, McpSession, ToolServer
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class AuthorityLapseError(RuntimeError):
    """Raised when a tool call is attempted on a session whose mTLS-bound
    authority (certificate validity + revocation epoch) has lapsed, even
    though the transport itself is still healthy."""
    pass


@dataclass
class CertBinding:
    fingerprint: str
    not_after: float          # epoch seconds
    revocation_epoch: int     # monotonic counter from the revocation feed


@dataclass
class McpSession:
    session_id: str
    binding: CertBinding
    scopes: Dict[str, bool] = field(default_factory=dict)
    opened_at: float = field(default_factory=time.time)
    max_age: float = 300.0    # server-enforced session cap, must be < cert lifetime

    def authority_expires_at(self) -> float:
        # Authority dies at the earlier of cert expiry or session max age.
        return min(self.binding.not_after, self.opened_at + self.max_age)


class ToolServer:
    def __init__(self, current_revocation_epoch: int):
        self._rev_epoch = current_revocation_epoch
        self._sessions: Dict[str, McpSession] = {}

    def open_session(self, session_id: str, binding: CertBinding,
                     scopes: Dict[str, bool]) -> McpSession:
        if binding.not_after <= time.time():
            raise AuthorityLapseError(
                f"refusing to open session {session_id}: cert already expired"
            )
        s = McpSession(session_id=session_id, binding=binding, scopes=scopes)
        self._sessions[session_id] = s
        return s

    def call_tool(self, session_id: str, tool: str, now: Optional[float] = None) -> str:
        now = time.time() if now is None else now
        s = self._sessions.get(session_id)
        if s is None:
            raise AuthorityLapseError(f"unknown session {session_id}")

        # The invariant that the naive cached-scope server omits:
        # re-validate the identity binding at EVERY call, not just at handshake.
        if now >= s.authority_expires_at():
            del self._sessions[session_id]
            raise AuthorityLapseError(
                f"session {session_id} authority lapsed at "
                f"{s.authority_expires_at():.0f} (now {now:.0f}); "
                f"cert notAfter={s.binding.not_after:.0f}, "
                f"max_age={s.max_age}s — re-handshake required"
            )
        if s.binding.revocation_epoch != self._rev_epoch:
            del self._sessions[session_id]
            raise AuthorityLapseError(
                f"session {session_id} bound to stale revocation epoch "
                f"{s.binding.revocation_epoch} != {self._rev_epoch}; evicted"
            )
        if not s.scopes.get(tool, False):
            raise AuthorityLapseError(
                f"session {session_id} lacks scope for tool {tool}"
            )
        return f"ok:{tool}@epoch={self._rev_epoch}"


# Demonstration of the silent-lapse boundary:
if __name__ == "__main__":
    t0 = time.time()
    server = ToolServer(current_revocation_epoch=42)
    binding = CertBinding(fingerprint="ab:cd", not_after=t0 + 60, revocation_epoch=42)
    sess = server.open_session("planner-7", binding, {"fs.write": True})

    # Call inside validity: succeeds.
    assert server.call_tool("planner-7", "fs.write", now=t0 + 30) == "ok:fs.write@epoch=42"

    # Call AFTER cert expiry but on the still-open session: must raise, not silently allow.
    try:
        server.call_tool("planner-7", "fs.write", now=t0 + 120)
    except AuthorityLapseError as e:
        print(f"correctly caught lapse: {e}")
    else:
        raise AuthorityLapseError("FAILED: lapsed authority was silently allowed")
