# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-signed-mcp-tool-manifest-toctou-drift-between-manifest-hash-and-runtime-skill-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-signed-mcp-tool-manifest-toctou-drift-between-manifest-hash-and-runtime-skill-attestation.warrant.json
# Markdown SHA-256:   0115f9c148a8d2bc5a850bc276bbe57f70956753cafa0863175bd1e552dc6359
# Code AST SHA-256:   02a711a1d6e1271fa2a0ef3d0f56f5b6ea4246f57637ce60771705fd6492ec2e
# Verified Classes:   AttestationError, SurfaceSuperset, SurfaceSubset, ImageDigestMismatch, CanonicalizationDrift, SignedManifest
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AttestationError(RuntimeError):
    """Base class for manifest/runtime attestation failures."""


class SurfaceSuperset(AttestationError):
    """Live server advertises tools absent from the signed manifest."""


class SurfaceSubset(AttestationError):
    """Live server omits tools the signed manifest declared."""


class ImageDigestMismatch(AttestationError):
    """Spawned process image does not match the signed image digest."""


class CanonicalizationDrift(AttestationError):
    """Signed and live schemas canonicalize differently."""


@dataclass(frozen=True)
class SignedManifest:
    tools: dict          # name -> structural schema hash
    image_digest: str    # sha256 of the executable/artifact
    signature_ok: bool


def canonical_hash(obj) -> str:
    # Structural hash: sorted keys, normalized numbers, no whitespace.
    blob = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def attest_server(manifest: SignedManifest, live_tools: dict, live_image_digest: str) -> None:
    if not manifest.signature_ok:
        raise AttestationError("manifest signature invalid; refusing to attest")

    if live_image_digest != manifest.image_digest:
        raise ImageDigestMismatch(
            f"image digest {live_image_digest!r} != signed {manifest.image_digest!r}"
        )

    signed_names = set(manifest.tools)
    live_names = set(live_tools)

    extra = live_names - signed_names
    if extra:
        raise SurfaceSuperset(f"undeclared tools present: {sorted(extra)}")

    missing = signed_names - live_names
    if missing:
        raise SurfaceSubset(f"declared tools absent at runtime: {sorted(missing)}")

    for name in signed_names:
        signed_h = manifest.tools[name]
        live_h = canonical_hash(live_tools[name])
        if signed_h != live_h:
            # Distinguish canonicalization drift from genuine schema change.
            if canonical_hash(json.loads(json.dumps(live_tools[name]))) != live_h:
                raise CanonicalizationDrift(f"schema hash unstable for {name!r}")
            raise AttestationError(
                f"schema mismatch for {name!r}: signed={signed_h} live={live_h}"
            )


def guarded_call(manifest, live_tools, live_image_digest, tool_name, args, invoke):
    attest_server(manifest, live_tools, live_image_digest)
    if tool_name not in manifest.tools:
        raise SurfaceSuperset(f"call to undeclared tool {tool_name!r} blocked")
    return invoke(tool_name, args)
