# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-credential-across-a-federated-trust-boundary-during-token-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-revoked-credential-across-a-federated-trust-boundary-during-token-rotation.warrant.json
# Markdown SHA-256:   54b912a952a8f36e380e88e0d7c1183ac4379dc5ce501dd669f16510b5339463
# Code AST SHA-256:   0ad591b075cbea9aa7acd5afe473c701b80185d07a9bd81dcaf8dd122fbd39c4
# Verified Classes:   StaleTrustStateError, Warrant, VerifierTrustState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleTrustStateError(RuntimeError):
    """Raised when a verifier cannot prove a credential is live at handoff time."""
    pass


@dataclass
class Warrant:
    instance_id: str
    issuer_epoch: int
    issued_at: float
    ttl: float

    def remaining_lifetime(self, now: float) -> float:
        return (self.issued_at + self.ttl) - now


@dataclass
class VerifierTrustState:
    revocation_epoch: int
    revocation_fetched_at: float
    key_set_fetched_at: float
    key_set_ttl: float
    propagation_budget: float  # max seconds revocation may take to reach us
    max_clock_skew: float


def verify_handoff(
    warrant: Warrant,
    state: VerifierTrustState,
    issuer_current_epoch: int,
    now: float,
) -> bool:
    # 1. Epoch ordering: verifier must not be behind issuer's revocation epoch.
    if state.revocation_epoch < issuer_current_epoch:
        raise StaleTrustStateError(
            f"verifier revocation epoch {state.revocation_epoch} < issuer epoch "
            f"{issuer_current_epoch}; credential liveness unprovable"
        )

    # 2. Key set must not be older than the warrant's remaining life can tolerate.
    key_age = now - state.key_set_fetched_at
    if key_age > state.key_set_ttl:
        raise StaleTrustStateError(
            f"key set age {key_age:.1f}s exceeds ttl {state.key_set_ttl:.1f}s"
        )

    # 3. Revocation state must be fresh enough to cover the warrant's remaining life.
    rev_age = now - state.revocation_fetched_at
    remaining = warrant.remaining_lifetime(now)
    if remaining <= 0:
        raise StaleTrustStateError("warrant expired at handoff")
    if rev_age + state.propagation_budget + state.max_clock_skew > remaining:
        raise StaleTrustStateError(
            f"revocation age {rev_age:.1f}s + propagation {state.propagation_budget:.1f}s "
            f"+ skew {state.max_clock_skew:.1f}s exceeds warrant remaining {remaining:.1f}s; "
            f"must re-fetch revocation state synchronously before executing capability"
        )

    return True
