# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-its-tee-backed-agent-identity-when-a-verifiable-credential-s-subject-binding-drifts-from-the-live-enc.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-its-tee-backed-agent-identity-when-a-verifiable-credential-s-subject-binding-drifts-from-the-live-enc.warrant.json
# Markdown SHA-256:   a6a7efb2077a4572f9b925f215d4a8f270de1b5fa65600c58f7a75144177d0aa
# Code AST SHA-256:   07acd357eeeaa44f1e071e7e340bd15bc10e1bfac41e7a82c6fb1d00f51cf915
# Verified Classes:   StaleBindingError, UntrustedMeasurementError, Quote, VerifiableCredential
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class StaleBindingError(RuntimeError):
    """Raised when a VC's embedded TEE measurement no longer matches the live enclave."""
    pass


class UntrustedMeasurementError(RuntimeError):
    """Raised when the live measurement is not in the issuer's allowlist."""
    pass


@dataclass
class Quote:
    measurement: str      # e.g. MRTD hex
    tcb_level: int
    nonce: str
    issued_at: float      # epoch seconds


@dataclass
class VerifiableCredential:
    subject: str
    cnf_pubkey: str
    embedded_measurement: str
    embedded_tcb: int
    not_before: float
    expires: float
    revoked: bool = False


FRESHNESS_WINDOW_S = 300.0
TCB_FLOOR = 0


def verify_live_binding(
    vc: VerifiableCredential,
    live_quote: Optional[Quote],
    expected_nonce: str,
    measurement_allowlist: set[str],
    now: Optional[float] = None,
) -> str:
    now = time.time() if now is None else now

    # 1. Credential structural validity (loud failures).
    if vc.revoked:
        raise StaleBindingError("credential revoked")
    if not (vc.not_before <= now <= vc.expires):
        raise StaleBindingError("credential outside validity window")

    # 2. Live quote must exist and be fresh and nonce-bound.
    if live_quote is None:
        raise StaleBindingError(
            "no fresh quote: embedded measurement cannot be used as live attestation"
        )
    if live_quote.nonce != expected_nonce:
        raise StaleBindingError("quote nonce mismatch: possible replay")
    if (now - live_quote.issued_at) > FRESHNESS_WINDOW_S:
        raise StaleBindingError("quote exceeds freshness window")

    # 3. TCB floor.
    if live_quote.tcb_level < TCB_FLOOR:
        raise UntrustedMeasurementError(
            f"live TCB {live_quote.tcb_level} below floor {TCB_FLOOR}"
        )

    # 4. Binding drift: the core boundary.
    if live_quote.measurement != vc.embedded_measurement:
        if live_quote.measurement in measurement_allowlist:
            # Legitimate drift (TCB update / relocation): force re-attestation.
            raise StaleBindingError(
                "measurement drift to allowlisted config; re-issue credential "
                f"bound to {live_quote.measurement} before proceeding"
            )
        raise UntrustedMeasurementError(
            f"live measurement {live_quote.measurement} not in allowlist; quarantine"
        )

    return "live-bound"
