FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

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.

ShareLinkedInFacebookX

In brief

  • Sign the exact byte string you send, in the form timestamp + '.' + body, and sign again on every retry.
  • Retry with exponential backoff and jitter over several days, cap the number of attempts and treat redirects as failures.
  • For a webhook sender, an arbitrary URL is a feature: resolve it, normalize it, reject internal IPs, then connect to the exact IP you checked.
Diagram: a webhook sender takes a client's URL and passes it through resolve_public (orange block), where every non-public IP is blocked. From there post_pinned connects to the client's endpoint using the exact IP that was vetted. Routes into the internal network (127.0.0.1, 169.254.169.254) are marked with an X.
resolve_public vets the IP once, then post_pinned opens a TCP connection to that exact IP. With no second DNS lookup, DNS rebinding has no chance to swap the destination for an internal network. Source: OWASP SSRF and webhook cheat sheet, per the article.

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.

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.

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.

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

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.

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.

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.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
4 sources
Read next on the roadmap · Stage 2: Broad engineeringThe async bug that hands one tenant's ID to another's requestIt never shows in a single-user demo; under production load, a per-request ContextVar reset with its token is what keeps tenants apart.