404human Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

Webhook security best practices: sender & app

How to secure both sides of webhooks: HMAC-SHA256 signing, replay timestamp windows, constant-time verify, idempotency, and SSRF/DNS rebinding.

Published
Read time
4 min read
Kind
guide
Topics

Webhooks break in two directions, and most guides only cover half the problem:

  • If you receive webhooks (from Stripe, GitHub, a payment sandbox, or a CMS), any unverified endpoint lets an attacker forge fake "payment.succeeded" events or replay yesterday’s valid webhook to credit an account twice.
  • If you send webhooks (letting tenants register callback URLs in your SaaS), every outbound delivery is a potential SSRF vector into your private network or cloud metadata service.

We built both sides across Payment Sandbox, Service Monitor, and Durable Runner. Here is the complete checklist—plus runnable signing and verification code—that covers receiver and sender security cleanly.

Receiver side: five rules for incoming webhooks

1. Sign timestamp + "." + raw_body with HMAC-SHA256

Never sign a re-serialized JSON object. Whitespace differences, key ordering, or Unicode escaping between sender and receiver will break valid signatures and tempt engineers into disabling verification. Always compute the HMAC over the exact raw request bytes concatenated with a Unix timestamp.

2. Enforce a tight replay timestamp window

An HMAC over the body alone proves authenticity, not freshness. Without a signed timestamp inside the MAC input, anyone who captures a valid webhook can replay it a week later. Reject any timestamp older (or further in the future) than 300 seconds (5 minutes).

3. Compare digests in constant time and support secret rotation

Never compare signature strings with == (which leaks timing information). Use hmac.compare_digest (Python), crypto.timingSafeEqual (Node), or subtle::ConstantTimeEq (Rust)—and accept an array of active secrets ([current_secret, previous_secret]) so you can rotate signing keys with zero downtime.

import hashlib
import hmac
import time


def sign_webhook(raw_body: bytes, secret: str, timestamp: int | None = None) -> str:
    """Sender side: produce header value 't=<unix>,v1=<hex_hmac>'."""
    ts = int(time.time()) if timestamp is None else timestamp
    signed_payload = f"{ts}.".encode("ascii") + raw_body
    digest = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
    return f"t={ts},v1={digest}"


def verify_webhook(
    raw_body: bytes,
    sig_header: str,
    secrets: list[str],
    tolerance_seconds: int = 300,
    now: int | None = None,
) -> bool:
    """Receiver side: check timestamp freshness and constant-time HMAC against active secrets."""
    parts = {}
    for item in sig_header.split(","):
        if "=" in item:
            k, v = item.strip().split("=", 1)
            parts.setdefault(k, []).append(v)

    if "t" not in parts or "v1" not in parts:
        return False
    try:
        ts = int(parts["t"][0])
    except ValueError:
        return False

    current_time = int(time.time()) if now is None else now
    if abs(current_time - ts) > tolerance_seconds:
        return False

    signed_payload = f"{ts}.".encode("ascii") + raw_body
    for secret in secrets:
        expected = hmac.new(secret.encode("utf-8"), signed_payload, hashlib.sha256).hexdigest()
        for candidate in parts["v1"]:
            if hmac.compare_digest(expected, candidate):
                return True
    return False

4. Make every webhook handler idempotent by event ID

Even with a 5-minute replay window, legitimate senders will deliver the same webhook twice when a response times out over the network. Store each processed event_id in a UNIQUE PostgreSQL table inside the same database transaction as the state update (idempotency keys in PostgreSQL):

INSERT INTO processed_webhooks (event_id, received_at)
VALUES ($1, now())
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;

If zero rows return, return 200 OK immediately without re-running business logic.

5. Acknowledge fast, process asynchronously, and bound body size

Return 2xx quickly after verifying the signature and durably enqueueing the event (via a transactional outbox or durable queue). Slow inline processing causes sender timeouts, which trigger retry storms. Also enforce a hard body-size cap (e.g., 256 KiB) before reading the payload into memory.

Sender side: five rules when your app sends webhooks

If your own product delivers webhooks to customer-supplied URLs, you have a different threat model: your customers are the potential attackers.

  1. Require HTTPS in production and reject non-HTTP schemes (file://, gopher://, ftp://).
  2. Enforce SSRF checks inside the DNS resolver, not before dialing. A pre-flight URL check is bypassed by DNS rebinding (TTL 0 switching from a public IP to 127.0.0.1), multi-record DNS answers ([public, 10.0.0.1]), IPv4-mapped IPv6 (::ffff:127.0.0.1), and cloud metadata (169.254.169.254). See our full Rust implementation in preventing webhook SSRF and DNS rebinding in Rust.
  3. Disable HTTP redirects on webhook deliveries (or re-run scheme + DNS + IP-blocklist validation on every redirect hop). A 302 to http://127.0.0.1:5432/ is the easiest SSRF bypass in the wild.
  4. Use strict connect/read timeouts, bounded response reads, and exponential backoff with jitter. Never let a slow webhook endpoint tie up worker threads or stream a 10 GB response body back into your delivery worker.
  5. Sign every outbound delivery with a unique per-endpoint secret (t=...,v1=...), store the secret encrypted at rest, and include a stable event_id header so receivers can deduplicate retries cleanly.

Quick webhook security checklist

SideControlProof test
ReceiverRaw-body HMAC-SHA256 + constant-time verifyFlip 1 byte in body or signature → assert 401
Receiver300 s timestamp toleranceSend valid HMAC with timestamp 10 min old → assert 401
ReceiverSecret rotation ([new, old])Sign with old secret during rotation window → assert 200
ReceiverTransactional event_id deduplicationSend exact same valid webhook twice concurrently → assert 1 state mutation
SenderResolver-level SSRF + no redirectsRegister http://169.254.169.254/, ::ffff:127.0.0.1, and 302 → 127.0.0.1 → assert all blocked

For the rest of your HTTP hardening checks, see our API security checklist with concrete tests.

Frequently asked questions

Is checking the sender’s IP address allowlist enough instead of HMAC signatures? No. IP allowlists break during provider infrastructure changes, can be bypassed if your reverse proxy misconfigures forwarding headers, and do not verify payload integrity. Treat IP allowlists as optional defense-in-depth; always verify HMAC-SHA256 signatures over the raw body and timestamp.

Why must I verify the signature on raw request bytes instead of parsed JSON? JSON parsers normalize whitespace, number formatting (1.0 vs 1), Unicode escape sequences, and object key order. Re-encoding parsed JSON rarely matches the sender’s exact bytes, causing valid signatures to fail.

What HTTP status code should a webhook receiver return on a duplicate event? Return 200 OK (or 204 No Content) once you confirm the event_id was already processed. Returning 409 or 500 makes the sender keep retrying an event you already handled.

Related reading