# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-mcp-tool-manifest-when-the-signing-key-rotates-mid-session-and-the-pinned-public-key-no-longer-matches.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-mcp-tool-manifest-when-the-signing-key-rotates-mid-session-and-the-pinned-public-key-no-longer-matches.warrant.json
# Markdown SHA-256:   7106ed9c4bb61aa037be9b4f2b7ed38f7a4b35ade37aa3bdf4a4bcd95c0f3026
# Code AST SHA-256:   9a23c7210c008ee9cf513b69c27828ecff3a9566a5bcd8728caa9b7a2c3ee1a5
# Verified Classes:   ManifestTrustError, CapabilityDriftError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import hmac


class ManifestTrustError(RuntimeError):
    """Raised when a tool manifest cannot be bound to a trusted, reasoned-about state."""
    pass


class CapabilityDriftError(ManifestTrustError):
    """Manifest authenticated (possibly via rotation) but schema hash differs from cached."""
    pass


def _hash_manifest(manifest: bytes) -> str:
    return hashlib.sha256(manifest).hexdigest()


def verify_manifest(
    manifest: bytes,
    signature: bytes,
    pinned_key: bytes,
    rotation_attestation: bytes | None,
    rotation_key: bytes | None,
    cached_hash: str,
) -> str:
    """
    Returns the new cached manifest hash on success.
    Raises ManifestTrustError (quarantine) or CapabilityDriftError (re-reason required).
    """
    new_hash = _hash_manifest(manifest)

    # Path 1: signature holds under the pinned key.
    if hmac.compare_digest(hmac.new(pinned_key, manifest, "sha256").digest(), signature):
        if new_hash != cached_hash:
            # Authenticated but drifted: caller MUST re-reason before dispatch.
            raise CapabilityDriftError(
                f"manifest authenticated but hash drifted: {cached_hash} -> {new_hash}"
            )
        return new_hash

    # Path 2: signature fails under pinned key; check for a rotation attestation.
    if rotation_attestation is not None and rotation_key is not None:
        att_ok = hmac.compare_digest(
            hmac.new(pinned_key, rotation_key, "sha256").digest(), rotation_attestation
        )
        sig_ok = hmac.compare_digest(
            hmac.new(rotation_key, manifest, "sha256").digest(), signature
        )
        if att_ok and sig_ok:
            # Authenticated under rotated key; still require re-reason on drift.
            if new_hash != cached_hash:
                raise CapabilityDriftError(
                    f"manifest authenticated under rotated key but hash drifted: "
                    f"{cached_hash} -> {new_hash}"
                )
            return new_hash

    # Path 3: no valid signature and no valid rotation chain -> quarantine.
    # Never downgrade to unverified; never merge the new manifest.
    raise ManifestTrustError(
        "manifest signature failed under pinned key with no valid rotation "
        "attestation; server quarantined, cached manifest retained"
    )


def dispatch_tool(tool_name: str, manifest: bytes, cached_hash: str, **kwargs) -> None:
    # Guardrail: refuse dispatch if the live manifest hash no longer matches
    # the hash the planner reasoned against.
    if _hash_manifest(manifest) != cached_hash:
        raise CapabilityDriftError(
            f"refusing dispatch of {tool_name!r}: live manifest hash diverged "
            f"from reasoned-against hash; re-plan required"
        )
    # ... actual tool invocation ...
