# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-dynamically-discovered-mcp-tool-after-the-permission-cache-has-already-been-warmed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-taints-a-dynamically-discovered-mcp-tool-after-the-permission-cache-has-already-been-warmed.warrant.json
# Markdown SHA-256:   e05029d59a0d3fa756e908a700a50619c503097363fd8619ea0f0681f90b79bd
# Code AST SHA-256:   f926aa2f34b29c170fcad6e59492f7bcd75911c062017aa09ee56756bfc0991c
# Verified Classes:   TaintCacheDivergence, ToolIdentity, PermissionCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class TaintCacheDivergence(RuntimeError):
    """Raised when a cached permission decision was keyed on an identity
    narrower than the identity the taint engine attributes to the call."""
    pass


@dataclass(frozen=True)
class ToolIdentity:
    endpoint: str
    name: str
    schema_hash: str
    instance_nonce: str

    @classmethod
    def from_declaration(cls, endpoint, name, input_schema, nonce):
        canonical = json.dumps(input_schema, sort_keys=True, separators=(",", ":"))
        return cls(
            endpoint=endpoint,
            name=name,
            schema_hash=hashlib.sha256(canonical.encode()).hexdigest(),
            instance_nonce=nonce,
        )


class PermissionCache:
    def __init__(self):
        self._entries = {}

    def put(self, identity: ToolIdentity, decision: dict):
        # Full identity, including nonce and schema hash. No normalization.
        self._entries[identity] = decision

    def get(self, identity: ToolIdentity) -> dict:
        return self._entries.get(identity)


def authorize(cache: PermissionCache, identity: ToolIdentity, taint_set: frozenset) -> dict:
    # Taint is evaluated BEFORE the cache lookup. A cache hit cannot bypass it.
    decision = cache.get(identity)
    if decision is None:
        raise TaintCacheDivergence(
            f"no cached decision for full identity {identity}; "
            f"refusing to fall back to a narrower key"
        )
    if taint_set and decision.get("taint_clear"):
        raise TaintCacheDivergence(
            f"cached allow for {identity.name}@{identity.instance_nonce} "
            f"claims taint_clear but call carries taint from {sorted(taint_set)}; "
            f"cache key and taint attribution disagree"
        )
    if taint_set and not decision.get("allow_tainted"):
        raise TaintCacheDivergence(
            f"tainted call to {identity.name} not permitted under least-privilege policy"
        )
    return decision


def handle_reconnect(cache: PermissionCache, old: ToolIdentity, new: ToolIdentity):
    # A reconnect changes the nonce; the old entry must not be reachable.
    if old.endpoint == new.endpoint and old.name == new.name and old.instance_nonce != new.instance_nonce:
        cache._entries.pop(old, None)
        return
    if old.schema_hash != new.schema_hash:
        cache._entries.pop(old, None)
        return
    raise TaintCacheDivergence(
        f"reconnect for {old.endpoint}/{old.name} did not change nonce or schema; "
        f"cannot prove identity stability"
    )
