# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-tool-manifest-whose-signature-verifies-but-whose-capability-set-exceeds-the-attested-grant-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-an-mcp-tool-manifest-whose-signature-verifies-but-whose-capability-set-exceeds-the-attested-grant-envelope.warrant.json
# Markdown SHA-256:   e24d783db57f5fb53dc729a4dbf22654c267e432b7d0ec2eb57a8259c481139a
# Code AST SHA-256:   731eee94987985a7fcf9379c450b195a61e4048b4fb415746805e709ac4c36ea
# Verified Classes:   ManifestAdmissionError, Warrant, Manifest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field

class ManifestAdmissionError(RuntimeError):
    """Raised when an MCP manifest is cryptographically valid but unauthorized."""
    pass

@dataclass
class Warrant:
    issuer_key: str
    may_delegate: frozenset[str]
    revoked: bool = False

@dataclass
class Manifest:
    issuer_key: str
    tools: dict[str, frozenset[str]]   # tool name -> declared capability closure
    envelope_scopes: frozenset[str]    # manifest's self-claimed grant (UNTRUSTED)
    inventory_hash: str
    signature_ok: bool

KNOWN_TOOL_CLOSURES = {
    "read_file": frozenset({"fs.read"}),
    "http_post": frozenset({"net.egress"}),
    "exec_shell": frozenset({"proc.spawn", "fs.write", "net.egress"}),
}

def normalize_tools(tools: dict[str, frozenset[str]]) -> frozenset[str]:
    closure = set()
    for name, declared in tools.items():
        if name not in KNOWN_TOOL_CLOSURES:
            # Unknown tool => unbounded closure => must reject, never guess.
            raise ManifestAdmissionError(f"unknown tool type '{name}': capability closure unbounded")
        closure |= KNOWN_TOOL_CLOSURES[name]
        closure |= set(declared)  # include declared, but never trust it alone
    return frozenset(closure)

def compute_inventory_hash(tools: dict[str, frozenset[str]], envelope: frozenset[str]) -> str:
    payload = repr((sorted((n, sorted(c)) for n, c in tools.items()), sorted(envelope)))
    return hashlib.sha256(payload.encode()).hexdigest()

def admit(manifest: Manifest, warrant: Warrant, policy_allow: frozenset[str],
          cache: dict[tuple[str, str], Manifest]) -> None:
    if not manifest.signature_ok:
        raise ManifestAdmissionError("signature verification failed")
    if warrant.issuer_key != manifest.issuer_key:
        raise ManifestAdmissionError("warrant issuer does not match manifest issuer")
    if warrant.revoked:
        raise ManifestAdmissionError("issuer warrant revoked")

    closure = normalize_tools(manifest.tools)
    authorized = warrant.may_delegate & policy_allow

    # THE BOUNDARY: subset check against the WARRANT, not manifest.envelope_scopes.
    if not closure <= authorized:
        excess = closure - authorized
        raise ManifestAdmissionError(
            f"capability escalation: {sorted(excess)} exceeds warranted grant envelope"
        )

    if manifest.inventory_hash != compute_inventory_hash(manifest.tools, manifest.envelope_scopes):
        raise ManifestAdmissionError("inventory hash does not cover normalized tool set")

    key = (manifest.issuer_key, manifest.inventory_hash)
    if key in cache and cache[key] != manifest:
        raise ManifestAdmissionError("cache replay mismatch for pinned inventory hash")

    cache[key] = manifest
