# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-peer-credential-as-still-valid-across-an-organizational-boundary-and-how-does-the-revocation-ep.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-revoked-peer-credential-as-still-valid-across-an-organizational-boundary-and-how-does-the-revocation-ep.warrant.json
# Markdown SHA-256:   6489aa94face4489da2661cc871807793fd852c656463623fae52996544d3854
# Code AST SHA-256:   72b72113e9ca9ff6103f9c603558ed643bfeb23eb8ca45f271a3c1c61ae4eb59
# Verified Classes:   RevocationStalenessError, ForeignCredential, TrustPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta


class RevocationStalenessError(RuntimeError):
    """Raised when a foreign credential's authority cannot be soundly bounded
    by the relying party's own revocation-cache staleness horizon."""


@dataclass(frozen=True)
class ForeignCredential:
    serial: str
    issuer_domain: str
    exp: datetime
    accepted_at: datetime
    revocation_refresh_at: datetime  # when this party last pulled issuer's revoke set


@dataclass(frozen=True)
class TrustPolicy:
    max_staleness: timedelta          # declared cache TTL for foreign revoke sets
    min_sound_headroom: timedelta     # refuse irreversible actions below this
    blast_radius: str                 # "reversible" | "irreversible"


def authorize_foreign_action(
    cred: ForeignCredential,
    policy: TrustPolicy,
    now: datetime,
) -> bool:
    if cred.issuer_domain == "self":
        return True  # local trust root, not federated

    # Sound lifetime is bounded by the *earlier* of credential expiry and
    # the moment our cached revocation set could be stale.
    stale_horizon = cred.revocation_refresh_at + policy.max_staleness
    sound_until = min(cred.exp, stale_horizon)
    headroom = sound_until - now

    if headroom <= timedelta(0):
        # Credential outlived the soundness bound; cache may be stale.
        raise RevocationStalenessError(
            f"credential {cred.serial} from {cred.issuer_domain} has no sound "
            f"lifetime: sound_until={sound_until.isoformat()} now={now.isoformat()}; "
            f"force on-demand revocation refresh before proceeding"
        )

    if policy.blast_radius == "irreversible" and headroom < policy.min_sound_headroom:
        raise RevocationStalenessError(
            f"credential {cred.serial} headroom {headroom} below required "
            f"{policy.min_sound_headroom} for irreversible action; "
            f"refresh revocation set or reject"
        )

    return True
