# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-federated-capability-attestation-that-validates-against-a-rotated-trust-anchor-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-federated-capability-attestation-that-validates-against-a-rotated-trust-anchor-mid-handoff.warrant.json
# Markdown SHA-256:   1f88e41f174e0291a238ff2f1b394a1fb5a47013653e60be177c2e87143c0ec9
# Code AST SHA-256:   1998b686313425a84cb09c273cd8a7bdc141f05e8ff9b53dc43c7812c9bfe170
# Verified Classes:   StaleAnchorEpochError, RevokedAttestationError, Attestation, AnchorState
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAnchorEpochError(RuntimeError):
    """Raised when a handoff is attempted under an attestation whose anchor
    epoch is no longer the issuer's current epoch (rotation occurred)."""
    pass


class RevokedAttestationError(RuntimeError):
    """Raised when the issuing org's revocation list marks the attestation
    as revoked at dispatch time, even if its signature still verifies."""
    pass


@dataclass(frozen=True)
class Attestation:
    issuer: str
    subject: str
    capability: str
    anchor_epoch: int
    exp: float
    signature_valid: bool


@dataclass(frozen=True)
class AnchorState:
    issuer: str
    current_epoch: int
    grace_epochs: frozenset  # epochs still published for verification only
    revocation_seen_epoch: int


def admit_handoff(
    att: Attestation,
    anchor: AnchorState,
    revoked_ids: set,
    now: float,
) -> str:
    """Decide Admit / Re-attest / Reject for a cross-org handoff.

    Returns 'admit' only when the attestation is valid under the *current*
    anchor epoch and is not revoked at dispatch time. Any stale-epoch or
    unknown-revocation condition raises so the caller re-attests rather
    than proceeding on a grace-window signature.
    """
    if att.issuer != anchor.issuer:
        raise RevokedAttestationError(
            f"issuer mismatch: attestation {att.issuer} vs anchor {anchor.issuer}"
        )

    if not att.signature_valid:
        raise RevokedAttestationError("signature invalid")

    if now >= att.exp:
        raise StaleAnchorEpochError(
            f"attestation expired at {att.exp}, now {now}"
        )

    # The discriminator: current epoch, not grace-window validity.
    if att.anchor_epoch != anchor.current_epoch:
        if att.anchor_epoch in anchor.grace_epochs:
            raise StaleAnchorEpochError(
                f"attestation minted under grace epoch {att.anchor_epoch}, "
                f"current epoch is {anchor.current_epoch}; re-attest required"
            )
        raise StaleAnchorEpochError(
            f"attestation epoch {att.anchor_epoch} unknown to issuer "
            f"{anchor.issuer} (current {anchor.current_epoch})"
        )

    # Revocation must be checked at dispatch, not at mint.
    if anchor.revocation_seen_epoch < anchor.current_epoch:
        raise StaleAnchorEpochError(
            f"revocation list for {anchor.issuer} is stale "
            f"(seen epoch {anchor.revocation_seen_epoch}, "
            f"current {anchor.current_epoch}); cannot confirm non-revocation"
        )

    att_id = (att.issuer, att.subject, att.capability, att.anchor_epoch)
    if att_id in revoked_ids:
        raise RevokedAttestationError(
            f"attestation {att_id} revoked at dispatch time"
        )

    return "admit"


# --- observed incident replay -------------------------------------------
def replay_incident():
    att = Attestation(
        issuer="org-c", subject="specialist-7", capability="ledger.read",
        anchor_epoch=7, exp=time.time() + 3600, signature_valid=True,
    )
    anchor = AnchorState(
        issuer="org-c", current_epoch=8, grace_epochs=frozenset({7}),
        revocation_seen_epoch=7,  # revocation list not yet refreshed
    )
    # Naive verifier would return 'admit' here (signature + exp OK).
    # Correct verifier raises, forcing re-attestation.
    return admit_handoff(att, anchor, revoked_ids=set(), now=time.time())


if __name__ == "__main__":
    try:
        replay_incident()
    except StaleAnchorEpochError as e:
        print(f"handoff blocked, re-attest required: {e}")
