# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-attestation-when-trust-anchor-rotation-outpaces-policy-cache-ttl.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-policy-attestation-when-trust-anchor-rotation-outpaces-policy-cache-ttl.warrant.json
# Markdown SHA-256:   e6fd61560c8e3e8953f151c860f562c1b9bce7225b971ee152d5ee0e60daac74
# Code AST SHA-256:   2097581c71739e9952536b8e426a6932e00f47e7409bd9dcd89f13fdd705fa20
# Verified Classes:   StaleAnchorEpochError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StaleAnchorEpochError(RuntimeError):
    """Raised when a peer attestation verifies against a cached anchor epoch
    that is older than the issuer's advertised current epoch."""
    pass


def verify_federated_attestation(
    attestation: dict,
    cached_anchor: dict,
    issuer_epoch_endpoint: dict,
    federation_meta: dict,
) -> str:
    # federation_meta must publish rotation interval and max propagation delay
    r_min = federation_meta.get("min_rotation_interval_s")
    p_max = federation_meta.get("max_propagation_delay_s")
    delta = federation_meta.get("allowed_epoch_skew_s")

    if r_min is None or p_max is None or delta is None:
        raise StaleAnchorEpochError(
            "federation metadata missing rotation bounds; cannot prove anchor currency"
        )
    if delta >= r_min:
        raise StaleAnchorEpochError(
            f"skew {delta}s >= rotation interval {r_min}s; provisional band spans a full rotation"
        )

    current_epoch = issuer_epoch_endpoint.get("current_epoch")
    if current_epoch is None:
        raise StaleAnchorEpochError(
            "issuer exposes no epoch endpoint; high-privilege grants unverifiable"
        )

    anchor_epoch = cached_anchor["epoch"]
    attestation_epoch = attestation["anchor_epoch"]

    if attestation_epoch != anchor_epoch:
        raise StaleAnchorEpochError(
            f"attestation signed under epoch {attestation_epoch} but verified "
            f"against anchor epoch {anchor_epoch}; epoch mismatch"
        )

    lag = current_epoch - anchor_epoch
    if lag == 0:
        return "accept"

    if 0 < lag <= delta:
        if attestation["grant_id"] in issuer_epoch_endpoint.get("revoked_grants", []):
            raise StaleAnchorEpochError(
                f"grant {attestation['grant_id']} revoked in current epoch "
                f"{current_epoch}; cached anchor epoch {anchor_epoch} is stale"
            )
        return "degraded_require_renegotiation"

    raise StaleAnchorEpochError(
        f"cached anchor epoch {anchor_epoch} lags issuer current epoch "
        f"{current_epoch} by {lag}s, exceeding skew {delta}s; refusing grant "
        f"{attestation['grant_id']}"
    )
