# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-stale-but-valid-signed-attestation-replay-across-federation-boundaries-when-the-warrant-ttl-outlives-the-capability-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-stale-but-valid-signed-attestation-replay-across-federation-boundaries-when-the-warrant-ttl-outlives-the-capability-re.warrant.json
# Markdown SHA-256:   babf3940c82b335df304f45a3691a538d364249cf0423b479a03367516d0c25c
# Code AST SHA-256:   d2584be552872ca3d9ef555e2283960755aa5f1802d589d9cad20b23f8b8b444
# Verified Classes:   StaleRevocationView, AttestationReplay, ClockSkewExceeded, Warrant, FederatedVerifier
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleRevocationView(RuntimeError):
    """Verifier's revocation list is too old to safely admit any warrant."""
    pass


class AttestationReplay(RuntimeError):
    """A warrant_id was presented twice, or by a non-bound presenter."""
    pass


class ClockSkewExceeded(RuntimeError):
    """Presented warrant timestamps are inconsistent with verifier clock."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    issuer: str
    audience: str
    presenter_instance_id: str
    issued_at: float
    not_after: float
    signature_ok: bool


class FederatedVerifier:
    MAX_CLOCK_SKEW = 5.0
    SAFETY_MARGIN = 30.0
    WARRANT_TTL_CAP = 900.0

    def __init__(self, revocation_list_age_fn, replay_cache):
        self._list_age = revocation_list_age_fn          # seconds since last authoritative fetch
        self._replay_cache = replay_cache                # warrant_id -> expiry
        self._now = time.time

    def admit(self, w: Warrant, presenter_pubkey_matches_warrant: bool) -> bool:
        now = self._now()

        # 1. Signature and structural checks (unchanged from prior baseline).
        if not w.signature_ok:
            raise StaleRevocationView(f"signature invalid for {w.warrant_id}")

        # 2. Clock-skew guard: reject warrants from the future or absurdly long-lived.
        if w.issued_at > now + self.MAX_CLOCK_SKEW:
            raise ClockSkewExceeded(
                f"{w.warrant_id} issued_at {w.issued_at:.0f} in future of {now:.0f}"
            )
        if (w.not_after - w.issued_at) > self.WARRANT_TTL_CAP:
            raise ClockSkewExceeded(
                f"{w.warrant_id} TTL {(w.not_after - w.issued_at):.0f}s exceeds cap"
            )

        # 3. Expiry.
        if now >= w.not_after:
            raise StaleRevocationView(f"{w.warrant_id} expired")

        # 4. Holder binding: proof-of-possession required, no bearer-style admission.
        if not presenter_pubkey_matches_warrant:
            raise AttestationReplay(
                f"{w.warrant_id} presented by unbound instance {w.presenter_instance_id}"
            )

        # 5. Revocation freshness gate — NO freshness fast-path based on issued_at.
        list_age = self._list_age()
        if list_age > (w.not_after - w.issued_at) - self.SAFETY_MARGIN:
            raise StaleRevocationView(
                f"revocation list age {list_age:.0f}s too stale for "
                f"{w.warrant_id} TTL {(w.not_after - w.issued_at):.0f}s"
            )

        # 6. Single-use enforcement: replay cache TTL >= warrant TTL + skew.
        cached_until = self._replay_cache.get(w.warrant_id)
        if cached_until is not None and now < cached_until:
            raise AttestationReplay(
                f"{w.warrant_id} already admitted; replay from {w.presenter_instance_id}"
            )
        self._replay_cache[w.warrant_id] = w.not_after + self.MAX_CLOCK_SKEW

        return True
