# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-a2a-push-callback-nonce-scope-collapse-across-the-webhook-authentication-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-replayed-a2a-push-callback-nonce-scope-collapse-across-the-webhook-authentication-boundary.warrant.json
# Markdown SHA-256:   90da671c6a90361d49889ba59f7e297ba4feaa6fbdcb5b5768d523060d0ae3d5
# Code AST SHA-256:   d538838e0a54015342c7b1cb0ed33140e509cad35116ede7f9912e9936481373
# Verified Classes:   ReplayBoundaryError, PushEnvelope, ReplayGuard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class ReplayBoundaryError(RuntimeError):
    """Raised when a push callback's replay guard is scoped narrower than its signature."""


@dataclass(frozen=True)
class PushEnvelope:
    sender_id: str
    task_id: str
    nonce: str
    iat: float
    body: bytes
    signature_valid: bool


class ReplayGuard:
    MAX_SKEW_S = 120.0

    def __init__(self) -> None:
        # Key MUST span every field the signature binds that a resender can vary.
        self._seen: dict[tuple[str, str, str, str], float] = {}

    def _cache_key(self, env: PushEnvelope) -> tuple[str, str, str, str]:
        body_hash = hashlib.sha256(env.body).hexdigest()
        return (env.sender_id, env.task_id, env.nonce, body_hash)

    def verify(self, env: PushEnvelope, now: float | None = None) -> None:
        now = time.time() if now is None else now

        if not env.signature_valid:
            raise ReplayBoundaryError(f"signature invalid for sender={env.sender_id}")

        skew = abs(now - env.iat)
        if skew > self.MAX_SKEW_S:
            raise ReplayBoundaryError(
                f"iat skew {skew:.1f}s exceeds {self.MAX_SKEW_S}s for task={env.task_id}"
            )

        key = self._cache_key(env)

        # Invariant check: a key that omits task_id or body_hash collapses the
        # replay domain below the signature domain -> reject the guard config.
        if key[1] == "" or key[3] == "":
            raise ReplayBoundaryError(
                "replay cache key collapsed: task_id/body_hash must be bound"
            )

        if key in self._seen and now - self._seen[key] <= self.MAX_SKEW_S:
            raise ReplayBoundaryError(
                f"replay detected sender={env.sender_id} task={env.task_id} nonce={env.nonce}"
            )

        self._seen[key] = now

    def check_handoff_snapshot(self, snapshot: dict) -> None:
        # A resumed agent must never inherit a reusable nonce from the snapshot.
        if snapshot.get("last_envelope_nonce") is not None:
            raise ReplayBoundaryError(
                "handoff snapshot carries reusable nonce; resumed sender must mint fresh nonce"
            )
