# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-accepting-a-revoked-peer-until-its-own-credential-rotates-stale-trust-anchor-caching-across-federated-a2a-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-accepting-a-revoked-peer-until-its-own-credential-rotates-stale-trust-anchor-caching-across-federated-a2a-domains.warrant.json
# Markdown SHA-256:   1a6ba81c588c92940b7dc5435ddc296d4367027a8c96618cb7c8280dd89125e9
# Code AST SHA-256:   6c5f5395466da823b8ee4b9b2295b55892ff9622ca1376af2711339eca703880
# Verified Classes:   StaleTrustBundleError, RevokedWarrantError, TrustBundle, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class StaleTrustBundleError(RuntimeError):
    """Raised when a warrant cannot be verified against a sufficiently fresh bundle."""


class RevokedWarrantError(RuntimeError):
    """Raised when a warrant's subject or signing key is revoked in the trusted snapshot."""


@dataclass
class TrustBundle:
    fetched_at: float
    active_keys: set
    revocations: dict  # subject -> revoked_at
    propagation_sla: float  # seconds; max acceptable staleness for this issuer


@dataclass
class Warrant:
    sub: str
    iss_key: str
    iat: float
    exp: float
    warrant_id: str


def verify_warrant(
    w: Warrant,
    bundle: TrustBundle,
    now: Optional[float] = None,
) -> bool:
    now = time.time() if now is None else now

    # Clause 1: not expired.
    if w.exp <= now:
        raise RevokedWarrantError(f"warrant {w.warrant_id} expired at {w.exp}")

    # Clause 4: bundle must be fresh enough to have observed a revocation.
    if now - bundle.fetched_at > bundle.propagation_sla:
        # Fail CLOSED: cannot prove freshness, so we must not authenticate.
        raise StaleTrustBundleError(
            f"bundle age {now - bundle.fetched_at:.1f}s exceeds SLA "
            f"{bundle.propagation_sla:.1f}s; refusing to authenticate {w.sub}"
        )

    # Clause 2: token must not postdate the snapshot used to verify it.
    if w.iat > bundle.fetched_at:
        raise StaleTrustBundleError(
            f"warrant {w.warrant_id} issued at {w.iat} after bundle snapshot "
            f"{bundle.fetched_at}; refetch required before acceptance"
        )

    # Clause 3a: signing key must still be active.
    if w.iss_key not in bundle.active_keys:
        raise RevokedWarrantError(
            f"signing key {w.iss_key} retired; warrant {w.warrant_id} rejected"
        )

    # Clause 3b: subject must not be revoked.
    if w.sub in bundle.revocations:
        raise RevokedWarrantError(
            f"subject {w.sub} revoked at {bundle.revocations[w.sub]}; "
            f"warrant {w.warrant_id} rejected"
        )

    return True
