# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-signed-mcp-tool-manifest-whose-attestation-covers-the-schema-but-not-the-runtime-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-signed-mcp-tool-manifest-whose-attestation-covers-the-schema-but-not-the-runtime-binding.warrant.json
# Markdown SHA-256:   3e8e185b18df202ef65fbfaac3007ca0fd5bf2b48c2dc6759c60a66a2fc1445b
# Code AST SHA-256:   645bf61278e588fe8a3ce84eb90a49285c5569da5825ef8f950e01b678f430fa
# Verified Classes:   ManifestAttestationScopeError, Attestation, RuntimeRef
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestAttestationScopeError(RuntimeError):
    """Raised when a signed manifest's attestation does not cover the executing runtime."""


@dataclass(frozen=True)
class Attestation:
    subject_digests: frozenset[str]  # sha256:... digests the signature actually covers
    signer: str


@dataclass(frozen=True)
class RuntimeRef:
    raw: str          # e.g. "oci://acme/mcp-fs:stable"
    is_immutable: bool
    resolved_digest: str | None  # None if raw is a mutable tag/label


def resolve_runtime(ref: str) -> RuntimeRef:
    if "@sha256:" in ref:
        return RuntimeRef(ref, True, "sha256:" + ref.split("@sha256:", 1)[1])
    return RuntimeRef(ref, False, None)


def full_manifest_digest(manifest: dict) -> str:
    # Load-bearing surface includes description and annotations, not just inputSchema.
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(canonical).hexdigest()


def admit_tool(manifest: dict, attestation: Attestation) -> None:
    runtime = resolve_runtime(manifest["server"]["runtime"])

    if not runtime.is_immutable or runtime.resolved_digest is None:
        raise ManifestAttestationScopeError(
            f"runtime {runtime.raw!r} is a mutable reference; "
            "attestation cannot transitively bind the executing artifact"
        )

    manifest_digest = full_manifest_digest(manifest)
    covered = attestation.subject_digests

    if manifest_digest not in covered:
        raise ManifestAttestationScopeError(
            f"full manifest digest {manifest_digest} not in attested subjects "
            f"{sorted(covered)}; description/annotations may be unsigned"
        )

    if runtime.resolved_digest not in covered:
        raise ManifestAttestationScopeError(
            f"runtime digest {runtime.resolved_digest} not in attested subjects "
            f"{sorted(covered)}; signature covers schema but not executing bytes"
        )

    # Both the full document and the executing artifact are attested: admissible.
