# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-verify-a-signed-mcp-tool-manifest-at-call-time-rather-than-at-session-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-verify-a-signed-mcp-tool-manifest-at-call-time-rather-than-at-session-handshake.warrant.json
# Markdown SHA-256:   350a6fe72591e1b309765ddfdeb1ae1f35e7c4d87ba2c1fd14294eca976feb33
# Code AST SHA-256:   0639b36709bfe6b59c091696d7a24a93336a896566b7e06f3a8f72238c614d99
# Verified Classes:   ManifestDigestMismatch, PublisherKeyRevoked, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ManifestDigestMismatch(RuntimeError):
    """Raised when the manifest about to execute does not match the attested digest."""
    pass


class PublisherKeyRevoked(RuntimeError):
    """Raised when the signing key chained to the manifest has been revoked."""
    pass


@dataclass(frozen=True)
class Attestation:
    name: str
    digest: str          # sha256 of canonical manifest bytes
    key_id: str
    verified_at: float


def canonical_digest(manifest_bytes: bytes) -> str:
    return "sha256:" + hashlib.sha256(manifest_bytes).hexdigest()


def authorize_invocation(
    tool_name: str,
    resolved_manifest_bytes: bytes,
    attestation: Optional[Attestation],
    revoked_key_ids: frozenset[str],
    manifest_is_immutable: bool,
) -> Attestation:
    """
    Call-time gate. Returns the attestation to execute against, or raises.
    Re-verifies whenever the execution target is mutable or evidence is missing.
    """
    live_digest = canonical_digest(resolved_manifest_bytes)

    # Immutable, digest-bound, already-attested: hoist the check.
    if (
        manifest_is_immutable
        and attestation is not None
        and attestation.digest == live_digest
    ):
        if attestation.key_id in revoked_key_ids:
            raise PublisherKeyRevoked(
                f"tool {tool_name!r} signed by revoked key {attestation.key_id!r}"
            )
        return attestation

    # Mutable target, missing evidence, or digest drift: must re-attest.
    if attestation is None:
        raise ManifestDigestMismatch(
            f"no attestation for tool {tool_name!r}; refusing to execute unverified manifest"
        )

    if attestation.digest != live_digest:
        raise ManifestDigestMismatch(
            f"tool {tool_name!r} manifest digest changed: "
            f"attested {attestation.digest!r} but resolved {live_digest!r}; "
            f"possible supply-chain tampering or unprocessed list_changed"
        )

    if attestation.key_id in revoked_key_ids:
        raise PublisherKeyRevoked(
            f"tool {tool_name!r} signed by revoked key {attestation.key_id!r}"
        )

    # Digest matches and key live: safe to execute.
    return attestation
