# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-mtls-client-certificate-as-insufficient-authorization-for-an-mcp-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-valid-mtls-client-certificate-as-insufficient-authorization-for-an-mcp-tool-call.warrant.json
# Markdown SHA-256:   4f5ec0000dc1b5900aca51130c420f4a65fbd24dbf2bdd07c278ee712c33d5f3
# Code AST SHA-256:   912fd78beb933b68efa8d55ea17d6ec8bcada877519db9b6cabd18be3908aa9f
# Verified Classes:   CapabilityError, CapabilityMissing, CapabilitySessionMismatch, CapabilityReplay, CapabilityScopeViolation, CapabilityToken, MCPSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class CapabilityError(RuntimeError):
    """Base for all per-message authority failures."""


class CapabilityMissing(CapabilityError):
    pass


class CapabilitySessionMismatch(CapabilityError):
    pass


class CapabilityReplay(CapabilityError):
    pass


class CapabilityScopeViolation(CapabilityError):
    pass


@dataclass(frozen=True)
class CapabilityToken:
    session_binding: str          # SHA256(cert_fp || server_nonce)
    msg_seq: int                  # monotonic per session
    tool: str
    resource: str
    expires_at: float


def derive_session_binding(cert_fingerprint: str, server_nonce: bytes) -> str:
    return hashlib.sha256(cert_fingerprint.encode() + server_nonce).hexdigest()


class MCPSession:
    def __init__(self, cert_fingerprint: str, server_nonce: bytes):
        self.cert_fingerprint = cert_fingerprint
        self.binding = derive_session_binding(cert_fingerprint, server_nonce)
        self.last_seq = 0

    def authorize(self, token: CapabilityToken | None, tool: str,
                  resource: str, now: float | None = None) -> None:
        # Session identity is established; authority is NOT implied by it.
        if token is None:
            raise CapabilityMissing(
                f"no capability token on message for tool={tool!r}; "
                "session identity alone is insufficient"
            )

        # Cross-session replay gate.
        if token.session_binding != self.binding:
            raise CapabilitySessionMismatch(
                f"token bound to {token.session_binding[:12]}… but session is "
                f"{self.binding[:12]}…; replay across sessions rejected"
            )

        # Intra-session replay gate.
        if token.msg_seq <= self.last_seq:
            raise CapabilityReplay(
                f"msg_seq={token.msg_seq} <= last_seq={self.last_seq}; "
                "token replayed within session"
            )

        # Freshness at message-arrival time, not session-open time.
        now = time.time() if now is None else now
        if token.expires_at <= now:
            raise CapabilityScopeViolation(
                f"token expired at {token.expires_at:.0f}, now {now:.0f}"
            )

        # Scope is (tool, resource), not the cert's coarse tool-set.
        if token.tool != tool or token.resource != resource:
            raise CapabilityScopeViolation(
                f"token scope ({token.tool!r},{token.resource!r}) does not cover "
                f"request ({tool!r},{resource!r})"
            )

        # Only now does authority advance.
        self.last_seq = token.msg_seq


def handle_tool_call(session: MCPSession, message: dict) -> str:
    meta = message.get("params", {}).get("_meta", {})
    raw = meta.get("capability")
    token = CapabilityToken(**raw) if raw else None
    tool = message["params"]["name"]
    resource = message["params"].get("arguments", {}).get("path", "")
    session.authorize(token, tool, resource)
    return f"executed {tool} on {resource}"


if __name__ == "__main__":
    sess = MCPSession("f_A", b"nonce-1")
    good = CapabilityToken(sess.binding, 1, "read", "/data/reports", time.time() + 60)
    print(handle_tool_call(sess, {
        "params": {"name": "read", "arguments": {"path": "/data/reports"},
                   "_meta": {"capability": good.__dict__}}}))
    # Missing token — the T+95s failure.
    try:
        handle_tool_call(sess, {"params": {"name": "exec",
                                           "arguments": {"path": "/etc"}}})
    except CapabilityMissing as e:
        print("REJECT:", e)
    # Replay of the same token — intra-session.
    try:
        handle_tool_call(sess, {
            "params": {"name": "read", "arguments": {"path": "/data/reports"},
                       "_meta": {"capability": good.__dict__}}})
    except CapabilityReplay as e:
        print("REJECT:", e)
