# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-signed-mcp-tool-schemas-from-surviving-capability-renegotiation-across-server-restarts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-signed-mcp-tool-schemas-from-surviving-capability-renegotiation-across-server-restarts.warrant.json
# Markdown SHA-256:   b99545b1daf5c238db5b077a750052e4c5b9f31863322c6071f23116a422c916
# Code AST SHA-256:   9504391b8f832ec2b29a5cb76f59684c5e86f229107e226e048b7386e3a373fd
# Verified Classes:   AttestationError, SignedEnvelope, VerifiedTool, ExecutionTable
# Defensive Guards:   5 fail-closed invariants (zero external deps)

"""Enforce MCP tool-schema attestation invariants across renegotiation.

Models the client-side execution table and the re-attestation transition.
Invariants I1-I5 are enforced as hard failures; no degraded trust path.
"""

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field


class AttestationError(RuntimeError):
    """Terminal failure: a tool-schema attestation invariant was violated."""


@dataclass(frozen=True)
class SignedEnvelope:
    """What the server ships. Epoch is inside the signed payload (I3)."""

    tool_digests: dict[str, str]      # tool name -> sha256 of canonical schema
    capabilities: frozenset[str]
    epoch: str
    key_id: str
    signature: bytes                  # Sig_K(payload) over the fields above


@dataclass
class VerifiedTool:
    digest: str
    epoch: str
    key_id: str


@dataclass
class ExecutionTable:
    """Client-side table of tools the agent is permitted to invoke (I1)."""

    pinned_keys: dict[str, bytes] = field(default_factory=dict)
    verified: dict[str, VerifiedTool] = field(default_factory=dict)
    live_epoch: str | None = None

    def verify_signature(self, env: SignedEnvelope) -> None:
        # I4: only pinned keys are admissible; no verify-on-first-use.
        if env.key_id not in self.pinned_keys:
            raise AttestationError(
                f"I4 violated: key_id {env.key_id!r} not in pinned key set"
            )
        payload = _canonical_payload(env)
        expected = self.pinned_keys[env.key_id]
        # Placeholder for real asymmetric verify; must be constant-time.
        if not _constant_time_eq(_sign(payload, expected), env.signature):
            raise AttestationError(
                f"signature verification failed for key_id {env.key_id!r}"
            )

    def reattest(self, env: SignedEnvelope, live_epoch: str) -> None:
        """Atomic re-attestation on renegotiation. Fail-closed (I2, I3)."""
        # I3: signed epoch must match the live server process epoch.
        if env.epoch != live_epoch:
            raise AttestationError(
                f"I3 violated: signed epoch {env.epoch!r} != live epoch {live_epoch!r}"
            )
        self.verify_signature(env)

        # I2: discard prior state BEFORE admitting new state.
        self.verified.clear()
        self.live_epoch = live_epoch

        for tool, digest in env.tool_digests.items():
            self.verified[tool] = VerifiedTool(
                digest=digest, epoch=env.epoch, key_id=env.key_id
            )

    def assert_invokable(self, tool: str, observed_digest: str) -> VerifiedTool:
        """I1: a tool absent from the verified table is uninvokable."""
        entry = self.verified.get(tool)
        if entry is None:
            raise AttestationError(
                f"I1 violated: tool {tool!r} present in tools/list but not attested"
            )
        if entry.digest != observed_digest:
            raise AttestationError(
                f"I1 violated: digest mismatch for {tool!r} "
                f"(attested {entry.digest[:12]}, live {observed_digest[:12]})"
            )
        return entry


def _canonical_payload(env: SignedEnvelope) -> bytes:
    parts = [env.epoch, env.key_id, *sorted(env.capabilities)]
    parts += [f"{k}={v}" for k, v in sorted(env.tool_digests.items())]
    return "\n".join(parts).encode()


def _sign(payload: bytes, key: bytes) -> bytes:
    return hashlib.sha256(payload + key).digest()  # stand-in for Ed25519


def _constant_time_eq(a: bytes, b: bytes) -> bool:
    if len(a) != len(b):
        return False
    diff = 0
    for x, y in zip(a, b):
        diff |= x ^ y
    return diff == 0


def handle_renegotiation(
    table: ExecutionTable, env: SignedEnvelope, live_epoch: str
) -> None:
    """Entry point for tools/list_changed / reconnect / transport reseat."""
    table.reattest(env, live_epoch)


if __name__ == "__main__":
    key = b"pinned-key-2026"
    table = ExecutionTable(pinned_keys={"k1": key})

    # Session 0: benign attestation.
    env0 = SignedEnvelope(
        tool_digests={"db.query": hashlib.sha256(b"v0").hexdigest()},
        capabilities=frozenset({"tools"}),
        epoch="E0",
        key_id="k1",
        signature=b"",
    )
    env0 = SignedEnvelope(**{**env0.__dict__, "signature": _sign(_canonical_payload(env0), key)})
    handle_renegotiation(table, env0, live_epoch="E0")
    table.assert_invokable("db.query", env0.tool_digests["db.query"])

    # Restart: behavior changed, epoch changed, but manifest was NOT re-signed.
    # Signed epoch is still E0 while live epoch is E1 -> I3 fires.
    try:
        handle_renegotiation(table, env0, live_epoch="E1")
    except AttestationError as e:
        print(f"blocked: {e}")
