# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-attestation-chain-break-when-the-tpm-endorsement-key-outlives-the-agent-s-credential-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-attestation-chain-break-when-the-tpm-endorsement-key-outlives-the-agent-s-credential-epoch.warrant.json
# Markdown SHA-256:   b99c429d7a850b6f76e89eabade8c8beebcd630c1284ca9b29105a83690590e2
# Code AST SHA-256:   96c0f8928b02852bbad307a70029924f304a361d16a380411300cb802610cd10
# Verified Classes:   StaleBindingError, VerifiableCredential, RuntimeContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleBindingError(RuntimeError):
    """Raised when a hardware-attested credential is presented outside the
    context-generation in which its key-to-instance binding was asserted."""


@dataclass(frozen=True)
class VerifiableCredential:
    subject_key_id: str
    policy_claims: dict
    context_gen: int          # runtime context-generation at issue time
    not_before: float
    not_after: float
    issuer_sig: bytes


@dataclass
class RuntimeContext:
    context_gen: int          # monotonic; bumped on restore/migrate/rebind
    tenant: str
    ak_handle: str            # hardware key handle, long-lived

    def bump(self, reason: str) -> None:
        # Any context-mutating event MUST invalidate prior bindings.
        self.context_gen += 1


def verify_at_use(
    vc: VerifiableCredential,
    ctx: RuntimeContext,
    now: float,
    quote_fresh: bool,
    quote_key_id: str,
) -> None:
    # Local invariants (what most implementations check):
    if not (vc.not_before <= now <= vc.not_after):
        raise StaleBindingError("credential outside validity window")
    if not quote_fresh:
        raise StaleBindingError("attestation quote is not fresh")
    if quote_key_id != vc.subject_key_id:
        raise StaleBindingError("quote key does not match credential cnf key")

    # Global invariant: the key-to-instance binding must have been asserted
    # in the *current* context generation. A fresh quote over a live key
    # does not prove the policy claims were re-derived for this context.
    if vc.context_gen < ctx.context_gen:
        raise StaleBindingError(
            f"credential minted at context_gen={vc.context_gen} but runtime "
            f"is at context_gen={ctx.context_gen}; re-attestation required "
            f"(tenant={ctx.tenant}, claims={vc.policy_claims})"
        )

    # Only now is the credential a valid statement about *this* instance.
    if vc.policy_claims.get("data_scope") != ctx.tenant:
        raise StaleBindingError(
            f"policy scope {vc.policy_claims.get('data_scope')} does not "
            f"match current tenant {ctx.tenant}"
        )


def resume_from_checkpoint(
    vc: VerifiableCredential,
    ctx: RuntimeContext,
    now: float,
) -> None:
    # Checkpoint restore is a context-mutating event: it may land on a
    # different host pool / tenant. Bump before any use of the cached VC.
    ctx.bump("checkpoint_restore")
    try:
        verify_at_use(
            vc=vc,
            ctx=ctx,
            now=now,
            quote_fresh=True,          # vTPM re-quotes on resume
            quote_key_id=vc.subject_key_id,
        )
    except StaleBindingError as exc:
        # Force re-attestation: discard cached VC, re-run quote + issuance.
        raise StaleBindingError(
            "cached credential invalid after resume; re-attestation required"
        ) from exc
