# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-signed-mcp-tool-descriptor-after-a-capability-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-re-signed-mcp-tool-descriptor-after-a-capability-downgrade.warrant.json
# Markdown SHA-256:   853546f766b9e199b3235f154e1df96e4e33c2334948a9dc68d6b20a4d1c4f63
# Code AST SHA-256:   8865855c1fd168b78a1ea27eaac3ab793a733570b1f5610589531d5c7406adea
# Verified Classes:   CapabilityDowngradeError, Grant, LiveBinding
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class CapabilityDowngradeError(RuntimeError):
    """Raised when a cached authorization grant no longer matches the live
    tool descriptor's capability bytes. Fails closed: the grant is void and
    the tool must not be invoked until policy re-evaluation completes."""
    pass


def _canonical(obj: Any) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")


def capability_digest(descriptor: dict) -> str:
    """Digest over the mutable capability fields only. Identity fields
    (server_id, tool_name) are deliberately excluded: they are the *key*,
    not the *value*, of the trust decision."""
    capability_bytes = {
        "inputSchema": descriptor.get("inputSchema"),
        "annotations": descriptor.get("annotations"),
        "permissions": descriptor.get("permissions"),
        "side_effects": descriptor.get("side_effects"),
    }
    return hashlib.sha256(_canonical(capability_bytes)).hexdigest()


@dataclass
class Grant:
    server_id: str
    tool_name: str
    capability_digest: str          # digest of the bytes this grant was derived from
    frozen_constraints: dict        # enforced at call time, NOT the live schema
    ttl_epoch: int
    signature_valid: bool = True


@dataclass
class LiveBinding:
    descriptor: dict
    grant: Grant | None = field(default=None)


def resume_and_assert(binding: LiveBinding, now: int) -> None:
    """Call on every session resume and before every invocation.
    Fails closed on any divergence between grant and live descriptor."""
    grant = binding.grant
    if grant is None:
        return  # no grant: policy engine must run, not this assertion's concern
    if not grant.signature_valid:
        raise CapabilityDowngradeError(
            f"{grant.server_id}/{grant.tool_name}: envelope signature invalid"
        )
    if now > grant.ttl_epoch:
        raise CapabilityDowngradeError(
            f"{grant.server_id}/{grant.tool_name}: grant expired; re-evaluate"
        )
    live_digest = capability_digest(binding.descriptor)
    if live_digest != grant.capability_digest:
        raise CapabilityDowngradeError(
            f"{grant.server_id}/{grant.tool_name}: capability downgrade detected "
            f"(grant={grant.capability_digest[:12]} live={live_digest[:12]}); "
            f"grant void, re-run policy against live bytes"
        )


def enforce_invocation(binding: LiveBinding, args: dict) -> None:
    """Enforce the grant's FROZEN constraints, never the live schema.
    The live schema is untrusted input; the frozen constraints are the
    authorization artifact."""
    grant = binding.grant
    if grant is None:
        raise CapabilityDowngradeError("no grant; refusing unauthenticated invocation")
    # Re-assert immediately before use: TTL may have elapsed mid-session.
    resume_and_assert(binding, now=grant.ttl_epoch)  # placeholder clock; real code passes now
    pattern = grant.frozen_constraints.get("path_pattern")
    if pattern is not None:
        import re
        path = args.get("path", "")
        if not re.fullmatch(pattern, path):
            raise CapabilityDowngradeError(
                f"path {path!r} violates frozen grant constraint {pattern!r}; "
                f"live schema is not authoritative"
            )
