# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-card-whose-attestation-chain-is-valid-but-whose-issuer-s-revocation-epoch-postdates-th.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-agent-card-whose-attestation-chain-is-valid-but-whose-issuer-s-revocation-epoch-postdates-th.warrant.json
# Markdown SHA-256:   97bf8f5da54729ced47142710ca3c51d9fadc984619afec9b4d61c2e53f4b259
# Code AST SHA-256:   3dd4cd897119d1824e195605cc3afa540904f63193b5946d707d1fc519c78e81
# Verified Classes:   FederatedCardTrustError, RevocationEntry, ChainLink, AgentCard
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class FederatedCardTrustError(RuntimeError):
    """Raised when a signed Agent Card's attestation chain is cryptographically
    valid but temporally invalid under the epoch-ordering invariant."""


@dataclass(frozen=True)
class RevocationEntry:
    key_id: str
    revocation_epoch: float
    issuer_signature: bytes  # signature over (key_id, revocation_epoch, reason)


@dataclass(frozen=True)
class ChainLink:
    key_id: str
    public_key: bytes
    attestation_signature: bytes  # countersignature by the next issuer up


@dataclass(frozen=True)
class AgentCard:
    leaf_key_id: str
    signing_epoch: float
    not_before: float
    not_after: float
    chain: tuple[ChainLink, ...]  # ordered leaf-adjacent first, root last


def verify_federated_card(
    card: AgentCard,
    revocation_set: dict[str, RevocationEntry],
    revocation_set_fetched_at: float,
    trust_anchors: set[str],
    now: Optional[float] = None,
    safety_margin: float = 30.0,
) -> None:
    """Verify a federated Agent Card under the epoch-ordering invariant.

    Raises FederatedCardTrustError on any violation, including the non-obvious
    case where a chain link was revoked at an epoch strictly after the card's
    signing epoch but at or before now.
    """
    now = time.time() if now is None else now

    if not card.chain:
        raise FederatedCardTrustError("empty attestation chain")

    # 1. Signature validity (assumed checked upstream; re-asserted here).
    for link in card.chain:
        if not link.attestation_signature:
            raise FederatedCardTrustError(
                f"link {link.key_id} missing countersignature"
            )

    # 2. Trust anchor must terminate the chain.
    root_key_id = card.chain[-1].key_id
    if root_key_id not in trust_anchors:
        raise FederatedCardTrustError(
            f"chain root {root_key_id} not in local trust anchors"
        )

    # 3. Leaf validity window.
    if not (card.not_before <= now < card.not_after):
        raise FederatedCardTrustError(
            f"card not valid at now={now}: window=[{card.not_before},{card.not_after})"
        )

    # 4. THE MISSING CONJUNCT: epoch-ordered revocation over the whole chain.
    # A link revoked at e is invalid for any t >= e, regardless of card expiry.
    for link in card.chain:
        entry = revocation_set.get(link.key_id)
        if entry is None:
            continue
        if entry.revocation_epoch <= card.signing_epoch:
            # Revoked before the card was countersigned: card was never valid.
            raise FederatedCardTrustError(
                f"link {link.key_id} revoked at {entry.revocation_epoch} "
                f"<= signing_epoch {card.signing_epoch}: card never valid"
            )
        if entry.revocation_epoch <= now:
            # Revoked after signing but before now: card was valid, now is not.
            raise FederatedCardTrustError(
                f"link {link.key_id} revoked at {entry.revocation_epoch} "
                f"in ({card.signing_epoch}, {now}]: post-signing revocation"
            )
        # revocation_epoch > now: future-dated rotation, card currently valid.

    # 5. Freshness bound: cache TTL must be tighter than remaining lifetime.
    remaining = card.not_after - now
    cache_age = now - revocation_set_fetched_at
    if cache_age > remaining - safety_margin:
        raise FederatedCardTrustError(
            f"revocation cache age {cache_age:.1f}s exceeds remaining card "
            f"lifetime {remaining:.1f}s minus margin {safety_margin}s: "
            f"trust-continuity gap"
        )


def accept_handoff(card: AgentCard, **kwargs) -> None:
    try:
        verify_federated_card(card, **kwargs)
    except FederatedCardTrustError as exc:
        # Fail closed: no tool calls, no warrant derivation, no state transfer.
        raise FederatedCardTrustError(
            f"handoff rejected: {exc}"
        ) from exc
