# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-warrant-mid-handoff-across-a-federation-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-warrant-mid-handoff-across-a-federation-trust-boundary.warrant.json
# Markdown SHA-256:   32e141ef7746d7cf0021cc84ebdc9d687a0bce7379326d9c2a8a702166baa98a
# Code AST SHA-256:   353731f3c9e847309fa5c1cd59eaa10f09c203e5d86751200c9b9996919f74d7
# Verified Classes:   StaleWarrantError, Warrant, LivenessAttestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when an inbound federated warrant cannot be proven live
    within the staleness bound delta, and the action is irreversible."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    action: str
    resource: str
    t_issued: float
    ttl: float
    renew_by: float          # max staleness delta the issuer will honor
    revocation_sla: float    # L_rev: max propagation latency issuer guarantees


@dataclass(frozen=True)
class LivenessAttestation:
    warrant_id: str
    t_attested: float
    live: bool


def authorize_irreversible_action(
    warrant: Warrant,
    attestation: LivenessAttestation | None,
    now: float,
    is_irreversible: bool = True,
) -> None:
    # TTL is necessary but NOT sufficient.
    if now > warrant.t_issued + warrant.ttl:
        raise StaleWarrantError(
            f"warrant {warrant.subject}->{warrant.action} expired by TTL"
        )

    if not is_irreversible:
        # Reversible actions may proceed on signature validity alone,
        # but must be flagged as unattested for the auditor.
        return

    if attestation is None:
        raise StaleWarrantError(
            "no liveness attestation; cannot prove delegation is current"
        )

    if not attestation.live:
        raise StaleWarrantError(
            f"issuer {warrant.issuer} reports warrant revoked"
        )

    delta = now - attestation.t_attested
    # The core invariant: staleness bound must be tighter than the
    # issuer's revocation propagation SLA, or a revoked-but-unseen
    # window exists.
    if delta >= warrant.renew_by:
        raise StaleWarrantError(
            f"attestation stale by {delta:.1f}s >= renew_by {warrant.renew_by:.1f}s"
        )
    if warrant.renew_by >= warrant.revocation_sla:
        raise StaleWarrantError(
            f"misconfigured warrant: renew_by {warrant.renew_by:.1f}s "
            f">= revocation_sla {warrant.revocation_sla:.1f}s; "
            "revocation gap is unbounded"
        )
