# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-credential-mid-handoff-the-aaif-revocation-echo-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-rotated-credential-mid-handoff-the-aaif-revocation-echo-window.warrant.json
# Markdown SHA-256:   3f870e8fdd3e39e6943287d22e78d5b9a3f422f1cdb766135fcccc54e69f66c8
# Code AST SHA-256:   37a6fbdb1461e858529d345ff5692a191aa18ba8914262e61c54e48a818a0460
# Verified Classes:   RevocationEchoError, Warrant, RevocationView
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class RevocationEchoError(RuntimeError):
    """Raised when a warrant passes static checks but its issuer's
    revocation state is too stale to trust (revocation-echo window)."""


@dataclass(frozen=True)
class Warrant:
    iss: str          # issuing identity, NOT key id
    sub: str
    aud: str
    scope: str
    iat: float
    exp: float
    jti: str


@dataclass(frozen=True)
class RevocationView:
    iss: str
    revoked: bool
    fetched_at: float   # t_rev: when the verifier observed this state


def validate_warrant(
    w: Warrant,
    verifier_id: str,
    requested_scope: str,
    rev_view: RevocationView,
    issuer_propagation_budget: float | None,  # Δ_prop, seconds; None = undeclared
    now: float | None = None,
    consumed_jtis: set[str] | None = None,
) -> None:
    now = time.time() if now is None else now

    # --- static checks (question 1) ---
    if not (w.iat <= now < w.exp):
        raise RevocationEchoError(f"warrant {w.jti} outside validity window")
    if w.aud != verifier_id:
        raise RevocationEchoError(f"warrant {w.jti} audience mismatch")
    if requested_scope not in w.scope:
        raise RevocationEchoError(f"warrant {w.jti} scope insufficient")
    if consumed_jtis is not None and w.jti in consumed_jtis:
        raise RevocationEchoError(f"warrant {w.jti} already consumed (replay)")

    # --- live revocation check (question 2) ---
    if rev_view.iss != w.iss:
        raise RevocationEchoError(
            f"revocation view for {rev_view.iss!r} does not cover issuer {w.iss!r}"
        )
    if rev_view.revoked:
        raise RevocationEchoError(f"issuer {w.iss} revoked; warrant {w.jti} is a zombie")

    # The core invariant: a *negative* revocation answer is only trustworthy
    # if it is fresher than the issuer's propagation budget.
    if issuer_propagation_budget is None:
        # Undeclared budget => any cached negative state is untrustworthy.
        # Only a check performed at verification time itself is acceptable.
        if rev_view.fetched_at < now:
            raise RevocationEchoError(
                f"issuer {w.iss} declares no propagation budget; "
                f"cached negative state at t_rev={rev_view.fetched_at} "
                f"cannot be trusted at t={now}"
            )
        return

    staleness = now - rev_view.fetched_at
    if staleness > issuer_propagation_budget:
        raise RevocationEchoError(
            f"revocation state for {w.iss} is {staleness:.1f}s stale "
            f"(budget {issuer_propagation_budget:.1f}s); "
            f"warrant {w.jti} may be a revocation echo"
        )


def relay_handoff(
    w: Warrant,
    relay_buffer_age: float,
    issuer_propagation_budget: float | None,
) -> None:
    """A relay agent must not buffer a warrant across a propagation window,
    because delivery-time revalidation is the only thing that catches an
    issuance that raced a revocation."""
    if issuer_propagation_budget is None:
        raise RevocationEchoError(
            "relay cannot buffer warrant for issuer with undeclared propagation budget"
        )
    if relay_buffer_age > issuer_propagation_budget:
        raise RevocationEchoError(
            f"warrant {w.jti} buffered {relay_buffer_age:.1f}s "
            f"(budget {issuer_propagation_budget:.1f}s); "
            f"revocation may have landed during buffer"
        )
