# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-cross-org-trust-federation-key-rotation-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-cross-org-trust-federation-key-rotation-mid-handshake.warrant.json
# Markdown SHA-256:   622421b483cddc01a9b061480da5d47e90200a8f3e8cca2f85ab7215c53a1d21
# Code AST SHA-256:   cf8df7df80c07e695e75f0dec4cd044129045ea97b55ae24936006b675297dc5
# Verified Classes:   StaleTrustEpoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleTrustEpoch(RuntimeError):
    """Raised when a peer Agent Card was signed under an anchor epoch
    that is older than the federation's current epoch, or when the card's
    key_id has been revoked in the current epoch. Distinct from a
    signature-verification failure: the bytes may verify fine, but the
    temporal authority is stale."""


def verify_federated_handshake(card, vp, anchor_resolver, crl):
    # Re-resolve anchor to its CURRENT epoch; never trust a cached snapshot
    # whose epoch is older than the card's claim.
    current = anchor_resolver.current_epoch()
    card_epoch = card.anchor_epoch

    if card_epoch < current.epoch:
        # Temporal authority lapsed. Do NOT retry the same handshake.
        raise StaleTrustEpoch(
            f"card signed under epoch {card_epoch}, current is {current.epoch}; "
            f"re-fetch card and re-resolve anchor before retrying"
        )

    if card.key_id in crl.revoked(current.epoch):
        raise StaleTrustEpoch(
            f"card key {card.key_id} revoked in epoch {current.epoch}"
        )

    # Now, and only now, check cryptographic validity against the SAME epoch.
    if not card.verify_signature(current.key_set):
        raise StaleTrustEpoch(
            f"card signature does not chain to epoch {current.epoch} key set; "
            f"card may be signed by a rotated-out key"
        )

    # Bind the live VP assertion to the same epoch and key chain.
    chain = vp.key_chain_to(card.key_id)
    if chain is None or not set(chain).issubset(current.key_set):
        raise StaleTrustEpoch(
            f"vp key {vp.key_id} not reachable from card key {card.key_id} "
            f"within epoch {current.epoch}"
        )

    return True
