# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-trust-root-divergence-from-silently-re-authorizing-a-revoked-agent-across-federated-did-resolvers.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-trust-root-divergence-from-silently-re-authorizing-a-revoked-agent-across-federated-did-resolvers.warrant.json
# Markdown SHA-256:   03ce2026de138b5c278312227123b118384bb36cfa8ec104e88e4f00e3644393
# Code AST SHA-256:   adce639a5773113b56056c7d7e7a552512306467d93b7fe677d7b9831a73e7d5
# Verified Classes:   TrustRootDivergenceError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class TrustRootDivergenceError(RuntimeError):
    """Raised when a signed agent card is verified against a DID document
    whose revocation epoch is below the card's key epoch, or when the
    verifier cannot prove freshness of its trust-root view."""


def authorize_agent_card(
    card: dict,
    did_doc: dict,
    observed_revocation_epoch: int,
    observed_epoch_source: str,
    resolver_source: str,
    observed_epoch_age_s: float,
    max_staleness_s: float = 300.0,
) -> bool:
    """Authorize a card only if signature validity AND trust-root freshness hold."""
    if observed_epoch_source == resolver_source:
        # Freshness must come from a failure domain independent of the resolver.
        raise TrustRootDivergenceError(
            f"freshness source {observed_epoch_source!r} shares failure domain "
            f"with resolver {resolver_source!r}; cannot bound revocation lag"
        )

    if observed_epoch_age_s > max_staleness_s:
        raise TrustRootDivergenceError(
            f"observed revocation epoch is {observed_epoch_age_s:.0f}s old "
            f"(> {max_staleness_s:.0f}s); trust root may be superseded"
        )

    card_key_epoch = card.get("key_epoch")
    if card_key_epoch is None:
        raise TrustRootDivergenceError(
            "card lacks key_epoch binding; cannot compare to revocation epoch"
        )

    if observed_revocation_epoch < card_key_epoch:
        raise TrustRootDivergenceError(
            f"card issued at key_epoch {card_key_epoch} but observed "
            f"revocation epoch is only {observed_revocation_epoch}; "
            f"card may be signed by a revoked key"
        )

    if observed_revocation_epoch > card_key_epoch:
        # Card is behind the trust root: re-resolve before trusting.
        raise TrustRootDivergenceError(
            f"card key_epoch {card_key_epoch} lags observed epoch "
            f"{observed_revocation_epoch}; re-resolve from independent source"
        )

    # Signature verification is a separate gate and must also pass.
    if not verify_signature(card, did_doc):
        raise TrustRootDivergenceError("card signature invalid against resolved DID document")

    return True
