# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-attestation-chain-silently-break-when-a-tpm-backed-key-outlives-the-workload-it-was-minted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-attestation-chain-silently-break-when-a-tpm-backed-key-outlives-the-workload-it-was-minted-for.warrant.json
# Markdown SHA-256:   f9011e223b6105efcf8e877d9a2c1ab6839439794cbf6417378430c58022141b
# Code AST SHA-256:   0a8c8e4b2b361bc1f4289cba2ef17f1586a9e161f117aed75c7cfbdcaa176e3e
# Verified Classes:   StaleWorkloadAttestationError, AttestationCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleWorkloadAttestationError(RuntimeError):
    """Raised when a hardware-backed credential is presented by a workload
    that did not mint it, i.e. the credential's workload_start_nonce does
    not match the presenting process's start nonce."""


@dataclass(frozen=True)
class AttestationCredential:
    subject_id: str            # workload instance UUID
    workload_start_nonce: str  # hex, generated at process start, bound into TPM quote
    platform_quote_pcrs: dict  # PCR index -> digest, from the quote
    issued_at: float
    expires_at: float
    issuer_signature: str      # opaque; assumed verified upstream


def verify_attestation(
    credential: AttestationCredential,
    presenting_start_nonce: str,
    approved_pcr_allowlist: dict,
    now: float | None = None,
) -> None:
    """Verify a workload attestation credential against the presenting process.

    Checks, in order:
      1. signature and issuer trust (assumed pre-verified; see issuer_signature)
      2. temporal validity (expires_at)
      3. platform integrity (PCRs match allowlist)
      4. workload liveness binding (nonce matches the presenting process)

    Step 4 is the one that is routinely omitted. Without it, a credential
    minted for a prior workload on the same host passes every other check,
    because the TPM quote is still valid: the platform did not change.
    """
    now = time.time() if now is None else now

    if now >= credential.expires_at:
        raise StaleWorkloadAttestationError(
            f"credential for subject={credential.subject_id} expired at "
            f"{credential.expires_at:.0f}, now={now:.0f}"
        )

    for pcr_index, expected_digest in approved_pcr_allowlist.items():
        actual = credential.platform_quote_pcrs.get(pcr_index)
        if actual != expected_digest:
            raise StaleWorkloadAttestationError(
                f"PCR[{pcr_index}] mismatch for subject={credential.subject_id}: "
                f"expected {expected_digest}, got {actual}"
            )

    # The liveness binding. A cached credential from a prior workload on the
    # same host carries the prior workload's nonce and fails here.
    expected_nonce = credential.workload_start_nonce
    if presenting_start_nonce != expected_nonce:
        raise StaleWorkloadAttestationError(
            f"workload_start_nonce mismatch: credential subject="
            f"{credential.subject_id} was minted for nonce={expected_nonce}, "
            f"but presenting process has nonce={presenting_start_nonce}. "
            f"Credential is a stale artifact of a prior workload on this host."
        )


def issue_attestation(
    subject_id: str,
    start_nonce: str,
    tpm_quote_pcrs: dict,
    ttl_seconds: float,
    issuer_sign,
) -> AttestationCredential:
    """Mint a credential bound to a specific workload start.

    The start_nonce MUST be included in the TPM quote's qualifying data so
    that the quote itself commits to it. Otherwise the nonce is just a
    claim by the workload, not a platform-attested fact.
    """
    now = time.time()
    cred = AttestationCredential(
        subject_id=subject_id,
        workload_start_nonce=start_nonce,
        platform_quote_pcrs=tpm_quote_pcrs,
        issued_at=now,
        expires_at=now + ttl_seconds,
        issuer_signature="",
    )
    return AttestationCredential(
        subject_id=cred.subject_id,
        workload_start_nonce=cred.workload_start_nonce,
        platform_quote_pcrs=cred.platform_quote_pcrs,
        issued_at=cred.issued_at,
        expires_at=cred.expires_at,
        issuer_signature=issuer_sign(cred),
    )


def new_start_nonce() -> str:
    return hashlib.sha256(
        f"{time.time_ns()}".encode() + b"workload-start"
    ).hexdigest()
