# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-tool-call-chain-silently-escalate-privilege-when-an-mcp-server-advertises-a-shadowed-tool-name-under-a-re-signed-c.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-delegated-tool-call-chain-silently-escalate-privilege-when-an-mcp-server-advertises-a-shadowed-tool-name-under-a-re-signed-c.warrant.json
# Markdown SHA-256:   4d783ad3aebf72aa016e8f97be1d7e2cb155250ede5a8ba8865f24c18b82e057
# Code AST SHA-256:   63075c54e6a994e5ec404012eab3131fe4d834f6e2f2d499882ee10e3a7ed85d
# Verified Classes:   ConfusedDeputyError, Descriptor, Warrant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ConfusedDeputyError(RuntimeError):
    """Raised when a deputy resolves a tool by name to a descriptor the warrant does not authorize."""


@dataclass(frozen=True)
class Descriptor:
    name: str
    body: bytes  # canonical serialized descriptor bytes; identity is derived from these

    def digest(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass(frozen=True)
class Warrant:
    tool_name: str
    descriptor_hash: str  # minted against the authorized descriptor, never re-anchored downstream


def execute_guarded(warrant: Warrant, presented: Descriptor, args: dict, executor) -> object:
    # Recompute identity from the bytes we will actually execute against.
    actual_hash = presented.digest()

    # Name match alone is insufficient; it is the confused-deputy trap.
    if warrant.tool_name != presented.name:
        raise ConfusedDeputyError(
            f"warrant names {warrant.tool_name!r} but presented tool is {presented.name!r}"
        )

    if actual_hash != warrant.descriptor_hash:
        raise ConfusedDeputyError(
            "descriptor hash mismatch: warrant authorizes "
            f"{warrant.descriptor_hash[:12]}… but presented descriptor hashes to "
            f"{actual_hash[:12]}… (possible tool-shadowing or hash forgery)"
        )

    # Only now, with identity verified on the same object, construct and run the call.
    return executor(presented, args)
