# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tee-attestation-that-is-valid-but-no-longer-binds-to-the-code-it-is-actually-running.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tee-attestation-that-is-valid-but-no-longer-binds-to-the-code-it-is-actually-running.warrant.json
# Markdown SHA-256:   da40e89abc4de73fabce168387a612fee4c97f6e08bd7c1dd02807a2893eea56
# Code AST SHA-256:   2fe5e399767f2b97ea29055f238e4cb22516a37d2a6d68933d17b82ddc5d6790
# Verified Classes:   StaleAttestationError, Quote, Receipt
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when a signed receipt's quote no longer covers its execution window."""


@dataclass(frozen=True)
class Quote:
    measurement: str
    report_data: str          # commits to signing key
    issued_at: float
    signature_valid: bool


@dataclass(frozen=True)
class Receipt:
    input_hash: str
    output_hash: str
    signing_key: str
    quote: Quote
    executed_at: float


ALLOWLIST = {"mrenclave:abc123"}
MAX_QUOTE_AGE_S = 300.0


def verify_receipt(receipt: Receipt, now: float | None = None) -> str:
    """Return 'attested' or 'authentic_unattested'; raise on hard failure."""
    now = time.time() if now is None else now
    q = receipt.quote

    if not q.signature_valid:
        raise StaleAttestationError("quote signature invalid")
    if q.measurement not in ALLOWLIST:
        raise StaleAttestationError(f"measurement {q.measurement!r} not allowlisted")

    expected_binding = hashlib.sha256(receipt.signing_key.encode()).hexdigest()
    if q.report_data != expected_binding:
        raise StaleAttestationError("report_data does not bind signing key")

    # The boundary: does the quote's validity window cover the execution?
    if receipt.executed_at < q.issued_at:
        raise StaleAttestationError("receipt predates its quote (impossible ordering)")
    if (receipt.executed_at - q.issued_at) > MAX_QUOTE_AGE_S:
        raise StaleAttestationError(
            f"quote issued {receipt.executed_at - q.issued_at:.0f}s before execution; "
            f"exceeds freshness window {MAX_QUOTE_AGE_S:.0f}s — measurement may have drifted"
        )
    if (now - q.issued_at) > MAX_QUOTE_AGE_S:
        # Session-lifetime cache would have hidden this; we surface it explicitly.
        return "authentic_unattested"

    return "attested"


def delegate(receipt: Receipt) -> None:
    disposition = verify_receipt(receipt)
    if disposition != "attested":
        raise StaleAttestationError(
            "refusing capability delegation: receipt is authentic but its quote "
            "does not bind the execution window"
        )
