# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-hardware-attestation-root-when-a-federated-peer-rotates-its-issuer-key-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-hardware-attestation-root-when-a-federated-peer-rotates-its-issuer-key-mid-session.warrant.json
# Markdown SHA-256:   90fd41a8f3549cb891a8b66f612b4469bf6b23ab91ed728d9148979a89a7b725
# Code AST SHA-256:   056c6de7ea8414391e2d17bee033a7012d2beda709068430d86e2e8141018e83
# Verified Classes:   StaleAttestationAnchorError, TrustBundle, AttestationQuote
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class StaleAttestationAnchorError(RuntimeError):
    """Raised when a peer's attestation chains to a trust anchor that is
    expired, revoked, or fetched outside the bundle's validity window."""
    pass


@dataclass(frozen=True)
class TrustBundle:
    issuer_id: str
    root_pubkey: bytes
    fetched_at: float
    ttl: float
    revoked_at: float | None = None

    def bundle_hash(self) -> str:
        return hashlib.sha256(
            self.issuer_id.encode() + self.root_pubkey + repr(self.fetched_at).encode()
        ).hexdigest()


@dataclass(frozen=True)
class AttestationQuote:
    issuer_id: str
    quoted_at: float
    signature_valid: bool
    nonce_fresh: bool


def verify_peer_attestation(
    quote: AttestationQuote,
    bundle: TrustBundle,
    now: float,
    privileged_op: bool,
) -> bool:
    # Gate 1: cryptographic acceptance.
    if not (quote.signature_valid and quote.nonce_fresh):
        raise StaleAttestationAnchorError(
            f"quote failed cryptographic gate for issuer {quote.issuer_id}"
        )

    # Gate 2: authorization acceptance (the boundary this record is about).
    if now > bundle.fetched_at + bundle.ttl:
        raise StaleAttestationAnchorError(
            f"trust bundle for {bundle.issuer_id} expired: "
            f"fetched_at={bundle.fetched_at}, ttl={bundle.ttl}, now={now}"
        )
    if bundle.revoked_at is not None and quote.quoted_at >= bundle.revoked_at:
        raise StaleAttestationAnchorError(
            f"quote for {bundle.issuer_id} produced after anchor revocation "
            f"(quoted_at={quote.quoted_at}, revoked_at={bundle.revoked_at})"
        )
    if quote.quoted_at < bundle.fetched_at - bundle.ttl:
        raise StaleAttestationAnchorError(
            f"quote predates bundle validity window for {bundle.issuer_id}"
        )

    # Privileged ops (baton pass, warrant delegation) require the anchor gate
    # to hold at operation time, not just at session establishment.
    if privileged_op and now > bundle.fetched_at + bundle.ttl:
        raise StaleAttestationAnchorError(
            f"privileged op blocked: anchor for {bundle.issuer_id} not current"
        )
    return True


def attempt_baton_pass(
    quote: AttestationQuote,
    bundle: TrustBundle,
    now: float,
    warrant_anchor_valid_until: float,
) -> str:
    verify_peer_attestation(quote, bundle, now, privileged_op=True)
    if warrant_anchor_valid_until < now:
        raise StaleAttestationAnchorError(
            f"warrant chains to anchor valid until {warrant_anchor_valid_until}, "
            f"now={now}; refusing baton pass to stale-anchored peer"
        )
    return f"baton passed under bundle {bundle.bundle_hash()}"
