# How to send webhooks without opening a door into your network

> Signing the exact bytes, retrying for nearly three days and connecting only to the IP you checked are three safeguards that fit in under a hundred lines of Python.

Original: https://fdetimes.net/en/guides/secure-webhook-sender-hmac-retries-ssrf/

OWASP's webhook security cheat sheet points out a paradox: for a system that sends webhooks, accepting any URL a user supplies is the feature itself, which makes senders especially exposed to SSRF. If a customer pastes `http://169.254.169.254/` into the configuration field, your server will dutifully call the cloud metadata endpoint.

Engineers who integrate their product into customers' systems will sooner or later have to build the sending side themselves. When that happens, the risk sits inside their own network, not the customer's.

This guide builds a webhook sender in three parts: Stripe-style HMAC signatures, a widening retry schedule, and a layer that blocks internal URLs. You need Python 3, the `requests` library and roughly an evening. The code is trimmed for readability, and every simplification is flagged.

## Sign the bytes you send, or nobody can verify them

Stripe signs each webhook with HMAC-SHA256 over a string made of the timestamp, a dot and the original body, then puts `t` and one or more `v1` signatures in the `Stripe-Signature` header.

Its documentation warns against reformatting or altering the payload before building that string. You can name the header whatever you like, but keeping this structure is wise, because the customer's engineers are likely to know it already.

**Step 1. The signing function.**

```python
import hmac, hashlib, json, time

def sign(secret: bytes, body: bytes, ts: int) -> str:
    msg = str(ts).encode() + b"." + body
    return hmac.new(secret, msg, hashlib.sha256).hexdigest()

def build_header(secrets: list[bytes], body: bytes) -> str:
    ts = int(time.time())
    sigs = ",".join(f"v1={sign(s, body, ts)}" for s in secrets)
    return f"t={ts},{sigs}"

body = json.dumps({"id": "evt_123", "type": "invoice.paid"}).encode()
```

The crucial detail is that `body` is serialized to bytes exactly once, and those same bytes are both signed and sent. Sign a dict and let the HTTP library run `json.dumps` again, and a single stray space is enough to break the signature.

The `secrets` parameter is a list because secrets sometimes have to be rotated. During a rotation, Stripe keeps the old secret alive for up to 7 days and, in that window, sends one signature per active secret, so the receiver needs only one to match. Customers can then switch to the new secret whenever it suits them without losing a single event.

**Step 2. Verification code to hand to the customer.** Write this function for them rather than leaving them to guess.

```python
def verify(secrets, body: bytes, header: str, tolerance=300) -> bool:
    parts = [p.split("=", 1) for p in header.split(",")]
    ts = int(next(v for k, v in parts if k == "t"))
    sigs = [v for k, v in parts if k == "v1"]
    ok = any(hmac.compare_digest(sign(s, body, ts), v)
             for s in secrets for v in sigs)
    return ok and abs(time.time() - ts) <= tolerance
```

Stripe requires signatures to be compared with a constant-time function, here `hmac.compare_digest`, and only then checks the clock skew to stop replays. Its libraries allow 5 minutes by default, hence `tolerance=300`. The timestamp is part of the signed string, so an attacker cannot change it.

**Check:** change one character in `body` and call `verify`; the result must be `False`. Pass a `ts` older than 6 minutes; that must return `False` too.

## How long should retries go on?

In live mode Stripe retries delivery for up to three days with exponential backoff, while its sandbox tries only 3 times over a few hours. The Standard Webhooks specification recommends much the same: a retry schedule spread over several days. OWASP adds three things: backoff with jitter, a cap on retries and per-subscriber rate limits.

Concrete parameters make this easier to picture: the first retry comes after 60 seconds, each later one doubles the wait, up to 12 retries. On paper, the total wait is 60 × (2¹² − 1) = 245,700 seconds, about 68 hours, close to Stripe's three-day window. The jitter in the code below adds at most 60 seconds per attempt, so it does not shorten that window.

Bear in mind that the gap between the last two attempts reaches roughly 34 hours. An endpoint that is down for a day or more will still receive its events, but possibly hours after it has come back.

**Step 3. A single delivery and the retry schedule.**

```python
import random, requests

MAX_RETRIES = 12

def attempt(url, body, secrets) -> bool:
    headers = {"Content-Type": "application/json",
               "Webhook-Signature": build_header(secrets, body)}
    r = requests.post(url, data=body, headers=headers,
                      timeout=15, allow_redirects=False)
    return 200 <= r.status_code < 300

def next_delay(n: int, base=60) -> float:
    return base * 2**n + random.uniform(0, base)  # jitter
```

Every line has a reason. The Standard Webhooks specification suggests a timeout of 15 to 30 seconds. Stripe treats redirect responses as failures, and OWASP advises disabling redirects or validating every redirect target as strictly as the original URL, so the code sets `allow_redirects=False` and accepts only 2xx codes.

The header is rebuilt inside `attempt`, so each retry carries a fresh timestamp and signature, as Stripe does. Store a signed header in the queue and resend it an hour later, and the receiver will reject the request for being more than 5 minutes out. The queue itself (a table with `next_attempt_at` and `attempts` columns, plus a worker that polls it) is left out here for brevity.

Retries mean duplicates. Stripe states plainly that webhooks may arrive more than once and out of order, so receivers need to record the event IDs they have processed. On your side, the `id` must stay the same across every attempt, and that belongs in the integration documentation you give the customer.

## The customer's URL is hostile input

**Key point:** When accepting unknown URLs is the feature, every URL must be treated as hostile until it has been checked.

OWASP describes the core defense: resolve the hostname, then reject every address that is not reachable from the public internet. The Standard Webhooks specification puts it more briefly: do not let webhooks reach internal networks and services.

**Step 4. Resolve and filter IPs.**

```python
import ipaddress, socket
from urllib.parse import urlsplit

def resolve_public(url: str):
    u = urlsplit(url)
    if u.scheme != "https" or not u.hostname:
        raise ValueError("invalid URL")
    port = u.port or 443
    ips = []
    for *_, sa in socket.getaddrinfo(u.hostname, port,
                                     proto=socket.IPPROTO_TCP):
        ip = ipaddress.ip_address(sa[0].split("%")[0])
        if ip.version == 6 and ip.ipv4_mapped:
            ip = ip.ipv4_mapped
        if not ip.is_global:
            raise ValueError(f"non-public address: {ip}")
        ips.append(ip)
    return u.hostname, port, ips
```

Do not skip the IPv6 normalization. According to OWASP's SSRF cheat sheet, `::ffff:169.254.169.254` points to the same host as its IPv4 form, so unless it is converted to IPv4 before the check, the cloud metadata IP can still slip through. Accepting only `https` is a choice made for this guide; you can relax it depending on your contract with the customer.

**Check:** call the function with `https://127.0.0.1/`, `https://169.254.169.254/` and `https://[::ffff:169.254.169.254]/`. All three must raise an error.

**Step 5. Connect to the IP you just checked.** OWASP warns that resolving the domain again just before the call still leaves the DNS rebinding hole open: at check time DNS returns a public IP, and when `requests` resolves the name a second time it may get `10.0.0.5`. The correct approach is to open the TCP connection to the filtered IP itself, while still using the hostname for SNI and TLS certificate validation.

```python
import http.client, ssl

def post_pinned(host, port, ip, path, body, headers, timeout=15):
    ctx = ssl.create_default_context()
    raw = socket.create_connection((str(ip), port), timeout=timeout)
    conn = http.client.HTTPSConnection(host, port, timeout=timeout,
                                       context=ctx)
    conn.sock = ctx.wrap_socket(raw, server_hostname=host)
    conn.request("POST", path, body=body, headers=headers)
    return conn.getresponse().status

def attempt(url, body, secrets) -> bool:
    host, port, ips = resolve_public(url)  # re-run on every attempt
    u = urlsplit(url)
    path = (u.path or "/") + (f"?{u.query}" if u.query else "")
    headers = {"Content-Type": "application/json",
               "Webhook-Signature": build_header(secrets, body)}
    return 200 <= post_pinned(host, port, ips[0], path,
                              body, headers) < 300
```

This `attempt` replaces the `requests` version from Step 3. Because `conn.sock` is already set, `http.client` neither connects nor resolves DNS on its own, and it does not follow redirects either. `resolve_public` runs again on every retry because the customer's DNS may change between attempts.

This is a simplified version: it tries only the first IP, does not reuse connections, and lets timeouts and TLS errors raise exceptions for the worker to count as a failed attempt. In production, a dedicated egress proxy applying the same checks is an alternative worth considering.

OWASP also notes that denylists are easy to bypass and should be a last resort; allowlists remain better. In enterprise settings, the practical approach is to have customers register their webhook domains in advance, accept only URLs on those domains, and still run the IP filter above.

## Mistakes to watch for, and where customers will notice them

The mistakes worth watching for all live in small details. Signing a dict instead of bytes. Comparing signatures with `==`. Letting the HTTP library follow a 302 redirect to an internal host. Retrying without jitter, so thousands of requests land in the same second just as the customer's endpoint comes back. Forgetting to normalize IPv4-mapped IPv6.

Before the first integration meeting, have answers ready for two questions. If the security team asks "how do we know the request comes from you?", hand over the `verify` function and the 7-day secret rotation policy.

If the operations team asks "what happens during weekend maintenance?", explain the roughly 68-hour retry schedule, with the caveat that events may arrive several hours after the endpoint recovers. Answering both with code and concrete numbers is the fastest way to win the trust of the customer's engineers.

For your career: if an FDE job posting mentions integrating with customer systems, the small repo from this guide is worth bringing to the interview.

On a CV, a line such as "built a webhook delivery system with HMAC signatures, multi-day retries and an SSRF-blocking layer, plus a verification SDK for customers" shows an interviewer that you think about both ends of an integration.

The code that receives webhooks is the customer's job. Making sure the sender does not turn your own server into a back door into the internal network is yours.

**Try this week:**

- Write the sign() and verify() functions from this guide, then change a single space in the body to watch the signature break
- Run resolve_public() against 127.0.0.1, 169.254.169.254 and ::ffff:169.254.169.254, and confirm all three are blocked
- Package the signing, retries and SSRF blocking into a small repo with a README, then add a one-line description of it to your CV

## Sources

- [Receive Stripe events in your webhook endpoint](https://docs.stripe.com/webhooks)

- [Standard Webhooks specification](https://raw.githubusercontent.com/standard-webhooks/standard-webhooks/main/spec/standard-webhooks.md)

- [Webhook Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Webhook_Security_Cheat_Sheet.html)

- [Server-Side Request Forgery Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html)
