# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-identity-mid-flight-across-a-federation-boundary-and-what-breaks-when-the-verifier-s-clock-and-the-signer-s-clock.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-identity-mid-flight-across-a-federation-boundary-and-what-breaks-when-the-verifier-s-clock-and-the-signer-s-clock.warrant.json
# Markdown SHA-256:   5a8466ded5700a1c54b42630709873b5dd61ddc8165a223a7e96eb5583356d04
# Code AST SHA-256:   5e2bed5a78a42c7dabaeccd6416b76b4d91bd1bcc94054e97847014a5af9588d
# Verified Classes:   AttestationSkewError, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationSkewError(RuntimeError):
    """Raised when a token's remaining lifetime is inside the skew uncertainty band."""
    pass


@dataclass
class Attestation:
    subject: str
    issued_at: float
    expires_at: float


def must_reattest_before_crossing(
    token: Attestation,
    issuer_now: float,
    max_skew: float,
    max_handoff_latency: float,
) -> bool:
    """
    Decide whether an agent must re-attest before crossing a federation boundary.

    Returns True if re-attestation is required, False if the token is safe to cross.
    Raises AttestationSkewError if the token is already inside the unsafe band and
    the caller attempted to cross without re-attesting.
    """
    if max_skew < 0 or max_handoff_latency < 0:
        raise AttestationSkewError(
            f"invalid skew/latency budget: skew={max_skew} latency={max_handoff_latency}"
        )

    remaining = token.expires_at - issuer_now
    safe_margin = 2.0 * max_skew + max_handoff_latency
    unsafe_floor = max_skew + max_handoff_latency

    if remaining <= 0:
        # Already expired on the issuer's own clock: never cross.
        raise AttestationSkewError(
            f"token for {token.subject} already expired on issuer clock "
            f"(remaining={remaining:.3f}s)"
        )

    if remaining <= unsafe_floor:
        # Inside the band where verifier clock offset can flip the decision.
        raise AttestationSkewError(
            f"token for {token.subject} inside skew band: "
            f"remaining={remaining:.3f}s <= skew+latency={unsafe_floor:.3f}s"
        )

    if remaining <= safe_margin:
        # Valid but margin is inside 2x skew: re-attest against verifier clock.
        return True

    return False


def cross_boundary(
    token: Attestation,
    issuer_now: float,
    max_skew: float,
    max_handoff_latency: float,
    reattest_fn,
) -> Attestation:
    """
    Cross a federation boundary, re-attesting if the remaining lifetime is
    inside the skew uncertainty band. Returns the token to present to the peer.
    """
    needs_reattest = must_reattest_before_crossing(
        token, issuer_now, max_skew, max_handoff_latency
    )
    if needs_reattest:
        fresh = reattest_fn(token.subject)
        if fresh.expires_at <= issuer_now:
            raise AttestationSkewError(
                f"re-attestation returned immediately-expired token for {token.subject}"
            )
        return fresh
    return token


if __name__ == "__main__":
    tok = Attestation(subject="agent-A", issued_at=1000.0, expires_at=1600.0)
    # 50s remaining, skew=70s, latency=5s -> inside skew band -> raises.
    try:
        cross_boundary(tok, issuer_now=1550.0, max_skew=70.0,
                       max_handoff_latency=5.0,
                       reattest_fn=lambda s: Attestation(s, 1550.0, 2150.0))
    except AttestationSkewError as e:
        print(f"blocked at boundary: {e}")
