# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-hardware-rooted-key-mid-task-and-what-breaks-if-it-defers-to-token-expiry.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-hardware-rooted-key-mid-task-and-what-breaks-if-it-defers-to-token-expiry.warrant.json
# Markdown SHA-256:   f853b2912176369ac3421ecb29838d8c1e90010684c91238d4bd1153be7c7a5b
# Code AST SHA-256:   a4435ae882f093ef437105e3a8bf92de88cfa3a5974b9bee099aad1766a2b92d
# Verified Classes:   StaleAttestationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time


class StaleAttestationError(RuntimeError):
    """Raised when a token's embedded measurement epoch no longer matches
    the executing platform's current measurement epoch."""
    pass


def current_epoch(pcr_set: dict) -> str:
    # Canonical hash over the measured boot state (PCR index -> value).
    h = hashlib.sha256()
    for idx in sorted(pcr_set):
        h.update(idx.to_bytes(2, "big"))
        h.update(pcr_set[idx])
    return h.hexdigest()


def renew_token(token: dict, pcr_set: dict, now: float) -> dict:
    """Renewal MUST re-validate the attestation epoch, not just token expiry.

    token = {"exp": float, "epoch": str, "quote": bytes, "key_sig": bytes}
    """
    if now >= token["exp"]:
        # Normal expiry path: must produce a FRESH quote, not reuse cached one.
        fresh_epoch = current_epoch(pcr_set)
        if fresh_epoch != token["epoch"]:
            # Epoch changed since last attestation; cached quote is invalid.
            raise StaleAttestationError(
                f"epoch mismatch on renewal: token epoch {token['epoch'][:12]} "
                f"!= current {fresh_epoch[:12]}; re-quote required"
            )
        return {**token, "exp": now + 900.0}

    # Not expired, but epoch may still have drifted (silent staleness).
    fresh_epoch = current_epoch(pcr_set)
    if fresh_epoch != token["epoch"]:
        # Fail closed: do NOT return the still-unexpired token.
        raise StaleAttestationError(
            f"unexpired token carries stale binding: {token['epoch'][:12]} "
            f"!= current {fresh_epoch[:12]}; halt and re-attest"
        )
    return token


def guarded_tool_call(token: dict, pcr_set: dict, call):
    # Every outbound call re-checks the epoch before spending the token.
    try:
        token = renew_token(token, pcr_set, time.time())
    except StaleAttestationError:
        # Cannot proceed under a decoupled identity; surface to orchestrator.
        raise
    return call(token)
