# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-attest-after-a-key-rotation-that-its-own-verifier-already-cached.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-attest-after-a-key-rotation-that-its-own-verifier-already-cached.warrant.json
# Markdown SHA-256:   35e3784fbf6925b625e675b7eff63d715b03a73a60f0932982ede0a6030bf9b1
# Code AST SHA-256:   5cb035e88c88e0dc8b8d8b28ee0fda217d91b0c7d620ab90334a7be4fff18985
# Verified Classes:   StaleAttestationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleAttestationError(RuntimeError):
    """Raised when a cached attestation cannot be reconciled with the presented key."""
    pass


def verify_warrant(warrant, cache, attest_fn):
    """
    warrant: dict with keys: subject, key_epoch, signing_key, signature, payload
    cache:   dict mapping (subject, key_epoch) -> {"key": pubkey, "measurement": str, "cred": dict}
    attest_fn: callable(signing_key) -> {"key": pubkey, "measurement": str, "cred": dict} or raises
    """
    cache_key = (warrant["subject"], warrant["key_epoch"])
    cached = cache.get(cache_key)

    if cached is not None:
        # Cache hit is only sound if the signature actually verifies against the cached key.
        if _verify_sig(warrant["payload"], warrant["signature"], cached["key"]):
            return cached
        # Signature does not match cached key: do NOT trust the cache, do NOT auto-abort.
        # Fall through to active re-attestation of the presented key.

    # Cache miss OR signature/cache mismatch -> full re-attestation of the presented key.
    try:
        fresh = attest_fn(warrant["signing_key"])
    except Exception as exc:
        raise StaleAttestationError(
            f"re-attestation failed for subject={warrant['subject']} "
            f"epoch={warrant['key_epoch']} key={warrant['signing_key']}: {exc}"
        ) from exc

    if fresh["key"] != warrant["signing_key"]:
        raise StaleAttestationError(
            f"attested key {fresh['key']} does not match presented key "
            f"{warrant['signing_key']} for subject={warrant['subject']}"
        )

    if not _verify_sig(warrant["payload"], warrant["signature"], fresh["key"]):
        raise StaleAttestationError(
            f"signature invalid against freshly attested key for subject={warrant['subject']}"
        )

    # Legitimate rotation (or first sight): replace the cache entry at the new epoch.
    cache[cache_key] = fresh
    return fresh


def _verify_sig(payload, signature, pubkey):
    # Placeholder for the real signature check (Ed25519/ECDSA over the enclave key).
    return signature is not None and pubkey is not None
