# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-verify-a-signed-tool-registry-attestation-mid-execution-rather-than-trusting-the-tuf-root-fetched-at-cold-start.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-verify-a-signed-tool-registry-attestation-mid-execution-rather-than-trusting-the-tuf-root-fetched-at-cold-start.warrant.json
# Markdown SHA-256:   3090c880ed5d6aebc9aaec730110ab9a51a67c072553f4544a8c3fdecfa55f0c
# Code AST SHA-256:   2916e2bdea325b355f1a2b250b77c3ad5ef6861e338930616bb6b6181062f4cd
# Verified Classes:   StaleAttestationError, CachedGrant, RegistryState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a cached tool attestation is no longer valid at invocation time."""


@dataclass(frozen=True)
class CachedGrant:
    tool_name: str
    manifest_digest: str
    root_version: int
    signing_key_id: str
    snapshot_expires: float  # epoch seconds
    cached_at: float


@dataclass(frozen=True)
class RegistryState:
    current_root_version: int
    trusted_key_ids: frozenset
    current_manifest_digest: str


def verify_tool_invocation(
    grant: CachedGrant,
    registry: RegistryState,
    now: Optional[float] = None,
) -> bool:
    """
    Tier-1 per-invocation check. Returns True only if the cached grant is
    still valid against current registry intent. Raises on any staleness.
    """
    now = now if now is not None else time.time()

    # Invariant 1: snapshot expiry bounds the cache. Fail closed, never fall back.
    if now >= grant.snapshot_expires:
        raise StaleAttestationError(
            f"snapshot for {grant.tool_name} expired at "
            f"{grant.snapshot_expires:.0f} (now {now:.0f}); "
            f"refusing invocation pending Tier-2 re-fetch"
        )

    # Invariant 2: cached root must not be behind registry root.
    if grant.root_version < registry.current_root_version:
        raise StaleAttestationError(
            f"cached root_version={grant.root_version} is behind "
            f"registry root_version={registry.current_root_version} for "
            f"{grant.tool_name}; cache invalidated"
        )

    # Invariant 3: signing key must still be trusted (revocation check).
    if grant.signing_key_id not in registry.trusted_key_ids:
        raise StaleAttestationError(
            f"signing key {grant.signing_key_id} for {grant.tool_name} "
            f"has been revoked at root_version={registry.current_root_version}"
        )

    # Invariant 4: manifest digest must match current registry manifest.
    if grant.manifest_digest != registry.current_manifest_digest:
        raise StaleAttestationError(
            f"manifest digest mismatch for {grant.tool_name}: "
            f"cached={grant.manifest_digest[:12]} "
            f"registry={registry.current_manifest_digest[:12]}"
        )

    return True


def invoke_with_lease(
    grant: CachedGrant,
    registry: RegistryState,
    call_fn,
    *args,
    **kwargs,
):
    """
    Wraps a tool call with Tier-1 verification and aborts on staleness.
    Mid-execution rotation is caught on the next invocation.
    """
    try:
        verify_tool_invocation(grant, registry)
    except StaleAttestationError:
        # Do not complete the call under a withdrawn grant.
        raise
    return call_fn(*args, **kwargs)
