Best Practices
There are many important considerations to take when implementing webhook consumers, and these have been well-documented and explained here: https://webhooks.fyi/best-practices/webhook-consumers. But outlined below are more specifics to setting up
Timestamp Checks
EquiDeFi webhook requests include a X-Webhook-Timestamp header that can be used to verify the timing of the request to help mitigate and block replay attacks.
Duplicate Sends
While uncommon, it is possible for events to be fired multiple times. This usually will only happen on failed webhook deliveries. The X-Webhook-Id can be used to block duplicate events from being processed in your application more than once.
Payload Verification
Since your endpoints need to be public, you can use the X-Webhook-Signature header in combination with the Signing SecretSigning Secret to verify the incoming request is valid and coming from EquiDeFi. Below are some example code snippets you can copy into your webhook endpoint to validate the request body coming in from EquiDeFi.
import hashlib
import hmac
import time
from typing import Optional
TOLERANCE_SECONDS = 300
def verify_equidefi_webhook(
raw_body: bytes, signature_header: Optional[str], secret: str, now: Optional[float] = None
) -> bool:
"""Verifies an EquiDeFi webhook. `raw_body` must be the request body bytes
exactly as received; a re-serialized JSON object will not match."""
if not signature_header:
return False
# X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
timestamp = None
signatures = []
for part in signature_header.split(","):
key, separator, value = part.strip().partition("=")
if not separator:
continue
if key == "t" and value.isdigit():
timestamp = int(value)
elif key == "v1" and value:
signatures.append(value)
if timestamp is None or not signatures:
return False
# Reject stale or future-dated deliveries to limit replays.
current = int(time.time() if now is None else now)
if abs(current - timestamp) > TOLERANCE_SECONDS:
return False
expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, signature) for signature in signatures)
# Flask:
#
# @app.post("/webhooks/equidefi")
# def equidefi_webhook():
# secret = os.environ["EQUIDEFI_WEBHOOK_SECRET"] # whsec_...
# if not verify_equidefi_webhook(request.get_data(), request.headers.get("X-Webhook-Signature"), secret):
# return "", 400
# event = request.get_json()
# # X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
# return "", 200