# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-peer-whose-mtls-leaf-is-valid-but-whose-trust-anchor-chain-diverges-from-the-token-s-issuer-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-a2a-peer-whose-mtls-leaf-is-valid-but-whose-trust-anchor-chain-diverges-from-the-token-s-issuer-binding.warrant.json
# Markdown SHA-256:   a46ffd308b9db7a667808a1055d195b529e7899f21a5d315504cb769577e5fe6
# Code AST SHA-256:   1bda657cee9c9e28bae59ccf3a11cdeb74b81fc95ceccb764f598da4eeebb227
# Verified Classes:   AnchorDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AnchorDivergenceError(RuntimeError):
    """Raised when mTLS leaf root and token issuer root differ without a valid equivalence assertion."""
    pass


def authorize_federated_peer(leaf_chain, token, anchors, equivalence_manifest, now):
    root_leaf = verify_chain(leaf_chain, anchors)
    issuer_key = resolve_issuer_key(token.iss, anchors)
    root_token = verify_chain(signing_cert_of(issuer_key), anchors)

    # Proof-of-possession is necessary but not sufficient.
    if not token.cnf_matches(leaf_chain[0]):
        raise AnchorDivergenceError(
            f"cnf thumbprint mismatch for aud={token.aud}"
        )

    if root_leaf.identity == root_token.identity:
        return True

    assertion = equivalence_manifest.find(root_leaf, root_token, scope=token.aud)
    if assertion is None:
        raise AnchorDivergenceError(
            f"anchor divergence: leaf_root={root_leaf.identity} "
            f"token_root={root_token.identity} aud={token.aud}; no equivalence assertion"
        )
    if assertion.expires_at <= now or not assertion.signed_by_trusted(anchors):
        raise AnchorDivergenceError(
            f"equivalence assertion for {root_leaf.identity}<->{root_token.identity} "
            f"expired or untrusted at {now}"
        )
    return True
