# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-valid-but-revoked-peer-credential-during-cross-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-valid-but-revoked-peer-credential-during-cross-agent-handoff.warrant.json
# Markdown SHA-256:   00a489b2615dd9e2d1f71c7a5165431f288eb5fbd2390f65e300f705a246ceec
# Code AST SHA-256:   5fb61ad9efa4a3736f3019df709eff1fd3f187ebd6ed052efca2cba394745c96
# Verified Classes:   RevocationLivenessError, WorkloadCredential, TrustView
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationLivenessError(RuntimeError):
    """Raised when a credential's liveness cannot be proven within budget."""
    pass


@dataclass
class WorkloadCredential:
    subject: str
    issued_at: float
    ttl: float
    revocation_epoch: int

    def expires_at(self) -> float:
        return self.issued_at + self.ttl


@dataclass
class TrustView:
    """A verifier's possibly-stale view of the control plane."""
    known_revocation_epoch: int
    cache_refreshed_at: float
    max_staleness: float

    def staleness(self, now: float) -> float:
        return now - self.cache_refreshed_at


def authenticate_for_mutation(
    cred: WorkloadCredential,
    view: TrustView,
    now: float,
    propagation_budget: float,
) -> None:
    # 1. Cryptographic/expiry check (stateless).
    if now >= cred.expires_at():
        raise RevocationLivenessError(
            f"credential for {cred.subject} expired at {cred.expires_at()}"
        )

    # 2. Liveness must be provable within the propagation budget for mutating actions.
    if view.staleness(now) > propagation_budget:
        raise RevocationLivenessError(
            f"revocation view for {cred.subject} is {view.staleness(now):.0f}s stale, "
            f"exceeds budget {propagation_budget:.0f}s; fail closed"
        )

    # 3. Epoch check: a delegated warrant must not outlive upstream revocation.
    if cred.revocation_epoch < view.known_revocation_epoch:
        raise RevocationLivenessError(
            f"credential epoch {cred.revocation_epoch} precedes known revocation "
            f"epoch {view.known_revocation_epoch} for {cred.subject}"
        )

    # 4. Staleness half-life gate: near-expiry mutating use forces re-auth.
    residual = cred.expires_at() - now
    if residual < cred.ttl / 2 and view.staleness(now) > 0:
        raise RevocationLivenessError(
            f"credential for {cred.subject} in staleness half-life "
            f"(residual {residual:.0f}s), cached revocation view not trusted"
        )
