# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-hardware-attestation-whose-measured-workload-digest-no-longer-matches-the-running-agent-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-hardware-attestation-whose-measured-workload-digest-no-longer-matches-the-running-agent-policy.warrant.json
# Markdown SHA-256:   798c4e17b6c35e8af9f4b187b8e63a5e4790a9121193fd840213f3f19c011cba
# Code AST SHA-256:   f3e344413b930357cb2d5307cba36e0fc9c61f47710272e8d15799fb8968d302
# Verified Classes:   AttestationBindingError, HardwareQuote, RegistryEntry, VerificationResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class AttestationBindingError(RuntimeError):
    """Raised when a hardware quote is cryptographically valid but its measured
    workload digest no longer binds to the peer's effective policy, or when the
    trust registry mapping is stale relative to the quote timestamp."""
    pass


@dataclass
class HardwareQuote:
    peer_id: str
    measured_digest: str          # digest over launch image + policy hash
    nonce: str
    quote_timestamp: float        # when the measurement was taken
    signature_valid: bool
    endorsement_chain_valid: bool


@dataclass
class RegistryEntry:
    peer_id: str
    policy_digest: str
    registered_at: float          # when this mapping was written


@dataclass
class VerificationResult:
    identity_verified: bool
    conformance_verified: bool
    reason: str


def verify_peer_attestation(
    quote: HardwareQuote,
    registry: RegistryEntry,
    expected_nonce: str,
    max_registry_lag_s: float = 5.0,
    max_quote_age_s: float = 2.0,
    now: Optional[float] = None,
) -> VerificationResult:
    now = time.time() if now is None else now

    # Layer 1: identity. Hardware-rooted, stable across credential lifetime.
    identity_ok = (
        quote.signature_valid
        and quote.endorsement_chain_valid
        and quote.nonce == expected_nonce
    )
    if not identity_ok:
        return VerificationResult(False, False, "identity attestation failed")

    # Layer 2: freshness of the measurement itself.
    if now - quote.quote_timestamp > max_quote_age_s:
        raise AttestationBindingError(
            f"quote for {quote.peer_id} is {now - quote.quote_timestamp:.2f}s old; "
            f"exceeds {max_quote_age_s}s conformance freshness bound"
        )

    # Layer 3: the measured digest must match the registry's policy mapping.
    if quote.measured_digest != registry.policy_digest:
        raise AttestationBindingError(
            f"measured digest {quote.measured_digest[:12]} for {quote.peer_id} "
            f"does not match registry policy {registry.policy_digest[:12]}; "
            f"peer likely reloaded policy without re-measurement"
        )

    # Layer 4: the registry mapping must not lag the quote — a mapping written
    # before the measurement cannot bind the measurement to a policy.
    if registry.registered_at < quote.quote_timestamp - max_registry_lag_s:
        raise AttestationBindingError(
            f"registry entry for {quote.peer_id} predates quote by "
            f"{quote.quote_timestamp - registry.registered_at:.2f}s; "
            f"mapping cannot bind current measurement to effective policy"
        )

    return VerificationResult(
        identity_verified=True,
        conformance_verified=True,
        reason="measurement bound to registry policy within freshness window",
    )


def authorize_behavior(result: VerificationResult, action: str) -> None:
    if not result.conformance_verified:
        raise AttestationBindingError(
            f"action '{action}' requires conformance attestation; "
            f"only identity was verified ({result.reason})"
        )
