# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-trust-anchor-rotation-skew-during-cross-org-federated-task-routing-before-policy-evaluation-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-trust-anchor-rotation-skew-during-cross-org-federated-task-routing-before-policy-evaluation-diverges.warrant.json
# Markdown SHA-256:   836148e185aafb531604b5d8eac60e3ca384d4dea2ae8ccb61407a71af3569ce
# Code AST SHA-256:   5db89f9d39b7e08d9b08388fd2a525a79e46a19c0168b5838ef0be66157828c3
# Verified Classes:   AnchorEpochSkewError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AnchorEpochSkewError(RuntimeError):
    """Raised when a federated warrant verifies against an anchor whose epoch
    does not match the epoch the active policy bundle was compiled against.
    Signature validity is necessary but not sufficient for authorization."""
    pass


def authorize_federated_task(warrant: dict, bundle: dict, jwks: dict) -> dict:
    issuer = warrant["issuer"]

    # Pass 1: authentication. Retired anchors in the overlap window are fine here.
    verified_key = _verify_signature(warrant, jwks)
    if verified_key is None:
        raise AnchorEpochSkewError(
            f"warrant from {issuer} failed signature verification against all live keys"
        )

    # Pass 2: epoch pinning. This is the invariant that bounds the failure.
    warrant_epoch = warrant["anchor_epoch"]
    bundle_epoch = bundle["compiled_against_epoch"].get(issuer)
    current_epoch = jwks["head_epoch"][issuer]

    if bundle_epoch is None:
        raise AnchorEpochSkewError(
            f"policy bundle has no compiled epoch for issuer {issuer}; "
            f"cannot authorize under unpinned anchor"
        )
    if warrant_epoch != bundle_epoch:
        raise AnchorEpochSkewError(
            f"anchor epoch skew for {issuer}: warrant minted under epoch "
            f"{warrant_epoch}, bundle compiled against epoch {bundle_epoch}. "
            f"Signature verified via kid={verified_key['kid']} but authorization "
            f"semantics are stale; refusing to evaluate scope intersection."
        )
    if warrant_epoch != current_epoch:
        raise AnchorEpochSkewError(
            f"warrant for {issuer} minted under non-head epoch {warrant_epoch} "
            f"(head={current_epoch}); issuer has rotated past the bundle. "
            f"Recompile policy bundle before routing."
        )

    # Pass 3: scope intersection, now safe because epochs are aligned.
    ceiling = bundle["issuer_ceiling"][issuer]
    effective = _intersect(warrant["scope"], ceiling)
    if not effective:
        raise AnchorEpochSkewError(
            f"empty effective scope for {issuer} task {warrant.get('task_id')}"
        )
    return {"issuer": issuer, "effective_scope": effective,
            "anchor_epoch": warrant_epoch, "kid": verified_key["kid"]}


def _verify_signature(warrant, jwks):
    for key in jwks["keys"][warrant["issuer"]]:
        if _sig_ok(warrant, key):
            return key
    return None
