# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-a2a-push-notification-after-webhook-key-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-a2a-push-notification-after-webhook-key-rotation.warrant.json
# Markdown SHA-256:   77f6aed695fec6048914e8ee6b7e1601f29d890a7c9835822f8a131a4fd8446c
# Code AST SHA-256:   574a9acd668e436ea5d6e0327f04019519e0e50e3d50a3eba2dafb499ea8a34c
# Verified Classes:   StalePushReplayError, ReplayGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StalePushReplayError(RuntimeError):
    """Raised when a signed push notification fails the freshness or replay gate."""


@dataclass
class ReplayGuard:
    # TTL must dominate credential grace + max retry age + clock skew.
    replay_ttl: float = 900.0
    max_skew: float = 120.0
    # Keyed by (sender_id, nonce) -- NEVER by kid.
    _seen: dict = field(default_factory=dict)
    _last_seq: dict = field(default_factory=dict)

    def _now(self) -> float:
        return time.monotonic()

    def check_and_record(
        self,
        sender_id: str,
        nonce: str,
        seq: int,
        iat_wall: float,
        now_wall: float,
        signature_valid: bool,
    ) -> None:
        # Gate A: authenticity (caller already verified JWS incl. grace kids).
        if not signature_valid:
            raise StalePushReplayError(
                f"signature invalid for sender={sender_id} nonce={nonce}"
            )

        # Gate B: freshness on receiver-controlled clock.
        if abs(now_wall - iat_wall) > self.max_skew:
            raise StalePushReplayError(
                f"iat outside skew window: delta={now_wall - iat_wall:.1f}s "
                f"nonce={nonce}"
            )
        last = self._last_seq.get(sender_id)
        if last is not None and seq <= last:
            raise StalePushReplayError(
                f"non-monotonic seq={seq} <= last_seq={last} sender={sender_id}"
            )

        # Gate C: replay cache keyed by identity+nonce, not credential.
        key = (sender_id, nonce)
        self._evict()
        if key in self._seen:
            raise StalePushReplayError(
                f"replayed nonce={nonce} sender={sender_id}"
            )

        self._seen[key] = self._now()
        self._last_seq[sender_id] = seq

    def _evict(self) -> None:
        cutoff = self._now() - self.replay_ttl
        for k in [k for k, t in self._seen.items() if t < cutoff]:
            del self._seen[k]

    def rotate_key(self, sender_id: str) -> None:
        # Rotation must NOT touch replay state. Explicit no-op guard.
        # Any implementation that clears _seen here reintroduces the defect.
        return None
