Webhooks: Receiving Events Safely with Signatures and Replay Protection
Receive events that a service pushes to your server: verify an HMAC signature in constant time, reject old timestamps to stop replays, process each event id once, and answer quickly, testing the cases against a real receiver and OpenSSL.
In this lesson you will
- Explain how webhooks differ from polling
- Verify a signature in constant time
- Reject replays with a timestamp window
- Process each event exactly once
About 28 minutes
Don’t call us, we’ll call you
To learn whether an order has been paid, Noor’s program could ask the payment provider every few seconds, which is called polling, and wastes requests and adds delay. A webhook turns this around: when something happens, the provider sends an HTTP POST with a JSON description of the event to a URL on Noor’s server. Her server is now the API, and the provider is the client. That brings a problem the earlier lessons did not have: anyone on the internet can send a POST to that URL, pretending to be the provider, for instance with a fake “payment succeeded” event.
Providers solve this with signatures. They give you a shared secret, and with every delivery they send a signature: an HMAC-SHA256 of the timestamp and the exact body, computed with that secret. Your server recomputes it and compares, using a constant-time function. If the body is changed by one character, or the secret is wrong, the signatures differ. A signature alone does not stop replay: an attacker who recorded a genuine delivery can send it again. So the timestamp is part of the signed text, and the receiver rejects deliveries older than a few minutes. Providers also deliver at least once, so the same event can arrive twice, and the receiver must process each event id only once. And the receiver must answer with a 2xx status quickly, doing slow work afterwards, because a slow or failing response makes the provider retry.
| Check | Protects against |
|---|---|
| HMAC signature of timestamp + body | Forged and tampered events |
| Timestamp within 5 minutes | Replay of recorded deliveries |
| Event id seen before? | Duplicate deliveries |
| Fast 2xx response | Needless provider retries |
| HTTPS | Eavesdropping |
import json, threading, hmac, hashlib, time, urllib.request, urllib.error, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = b"whsec_demo_secret"
TOLERANCE = 300
NOW = [1_700_000_000] # the receiver's clock, fixed so the lesson is repeatable
processed, rejected = [], []
def sign(ts, body, secret=SECRET): return hmac.new(secret, ("%d." % ts).encode() + body, hashlib.sha256).hexdigest()
class Receiver(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers["Content-Length"]))
try:
parts = dict(p.split("=", 1) for p in self.headers.get("X-Signature", "").split(","))
ts, sig = int(parts["t"]), parts["v1"]
except Exception:
return self.finish_with(400, "malformed signature header")
if not hmac.compare_digest(sig, sign(ts, body)): return self.finish_with(401, "bad signature")
if abs(NOW[0] - ts) > TOLERANCE: return self.finish_with(400, "timestamp outside tolerance")
event = json.loads(body)
if event["id"] in [e["id"] for e in processed]: return self.finish_with(200, "duplicate ignored")
processed.append(event); self.finish_with(200, "processed")
def finish_with(self, code, why):
if code != 200 or why != "processed": rejected.append(why)
b = why.encode(); self.send_response(code); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Receiver); url = "http://127.0.0.1:%d/webhook" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def deliver(body, ts, secret=SECRET, tamper=None):
sig = sign(ts, body, secret)
sent = tamper(body) if tamper else body
req = urllib.request.Request(url, data=sent, headers={"X-Signature": "t=%d,v1=%s" % (ts, sig)})
try: r = urllib.request.urlopen(req); return r.status, r.read().decode()
except urllib.error.HTTPError as e: return e.code, e.read().decode()
evt = json.dumps({"id": "evt_001", "type": "payment.succeeded", "order": "A-1001", "amount_cents": 4200}).encode()
tests = [
("genuine delivery", deliver(evt, NOW[0])),
("same event again (duplicate)", deliver(evt, NOW[0])),
("body changed in transit", deliver(evt, NOW[0], tamper=lambda b: b.replace(b"4200", b"1"))),
("signed with the wrong secret", deliver(evt, NOW[0], secret=b"guess")),
("recorded delivery replayed an hour later", deliver(evt.replace(b"evt_001", b"evt_002"), NOW[0] - 3600)),
("no signature at all", (lambda: urllib.request.urlopen(urllib.request.Request(url, data=evt)))),
]
rows = []
for label, res in tests:
if callable(res):
try: res()
except urllib.error.HTTPError as e: res = (e.code, e.read().decode())
rows.append((label, res[0], res[1])); print(label.ljust(42), res[0], res[1])
print("events processed:", [e["id"] for e in processed], "| amount recorded:", processed[0]["amount_cents"])
body = evt; ts = NOW[0]
mine = sign(ts, body)
ssl_out = subprocess.run(["openssl", "dgst", "-sha256", "-hmac", SECRET.decode(), "-hex"], input=("%d." % ts).encode() + body, capture_output=True).stdout.decode().split("= ")[1].strip()
print("OpenSSL computes the same signature:", ssl_out == mine)
print("DATA " + json.dumps({"rows": rows, "processed": [e["id"] for e in processed], "ssl": ssl_out == mine}))
srv.shutdown()
genuine delivery 200 processed
same event again (duplicate) 200 duplicate ignored
body changed in transit 401 bad signature
signed with the wrong secret 401 bad signature
recorded delivery replayed an hour later 400 timestamp outside tolerance
no signature at all 400 malformed signature header
events processed: ['evt_001'] | amount recorded: 4200
OpenSSL computes the same signature: True
Six deliveries were sent to a real receiver on a local port, each representing a situation that a webhook endpoint meets. The genuine delivery was verified and processed. The same event sent again, which providers do when they think a delivery failed, was recognised by its id and answered with 200, “duplicate ignored”: the receiver acknowledges it so that the provider stops retrying, but does not process it twice, so the order is not shipped twice. A delivery whose body was altered in transit, a payment of 4,200 changed to 1, failed the signature check with status 401, and so did one signed with the wrong secret.
The replay case is the subtle one. The sixth event carried a valid signature, because it was signed by someone holding the secret, but its timestamp was an hour old, so the receiver refused it with 400 and “timestamp outside tolerance”. An attacker who recorded a genuine delivery could resend it, and without the timestamp window it would pass the signature check. A delivery with no signature header at all was refused as malformed. At the end, only evt_001 was processed, with the amount 4,200 cents, exactly once, out of six attempts. The order of the checks matters too: the receiver verifies the signature before it trusts anything in the body, including the timestamp inside it.
Independent check: OpenSSL, a separate implementation of HMAC-SHA256, computed the signature of the same timestamp and body with the same secret and produced the same hex digest as Python (“OpenSSL computes the same signature: True”), so the signing scheme can be implemented by the provider in any language. The result of each case is also what the specification of the receiver says: a table of six situations and the status that each deserves, which the output reproduces exactly.
Check by hand: the signed text is the timestamp, a dot and the raw body bytes. A tolerance of 300 seconds means that a timestamp one hour (3,600 seconds) old is outside it, so it is refused, and one 100 seconds old would be accepted. Comparing with hmac.compare_digest takes the same time wherever the first difference is, so an attacker learns nothing from timing.
Compute the signature over the exact bytes received. If you parse and re-serialise the JSON first, whitespace and key order can differ and the signature will not match, or worse, you will verify something other than what you process.
Return 2xx as soon as the event is verified and stored, and process it in the background. A slow handler causes timeouts, retries and duplicates.
Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. The signature header format here is a common pattern and not any particular provider’s. Each provider documents its own format, secret rotation and retry rules.
Practice
Store processed event ids in a database with a unique constraint instead of a list. Support two secrets at once, so that a secret can be rotated. Write a test that sends a delivery 299 and 301 seconds old.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Why sign webhook deliveries?
- To compress them
- To speed them up
- To encrypt them
- So the receiver can tell genuine events from forged ones
HMAC with a shared secret.
Why include a timestamp in the signed text?
- To sort events
- To save space
- To reject replays of old deliveries
- To encrypt
Within a tolerance of minutes.
Why must a receiver process each event id only once?
- Ids are random
- JSON requires it
- Providers deliver at least once
- It saves memory
Duplicates happen.
What should the receiver answer for a duplicate?
- An error
- 2xx, so the provider stops retrying
- Nothing
- 404
Acknowledge, do not process again.
Why use a constant-time comparison?
- It is shorter
- To avoid leaking how many characters matched
- It handles JSON
- It is faster
Timing attacks.
Summary
- Webhooks push events to your server, so you become the API.
- Verify an HMAC over the raw body in constant time.
- Reject old timestamps and process each event id once.
- Answer quickly with a 2xx and work afterwards.
Questions
What if my server is down when an event is sent?
Most providers retry with backoff for hours or days. Make sure your handler is idempotent, and use the provider's dashboard to resend missed events.
Should I trust the event body or call the API to confirm?
A common safe pattern is to verify the signature and then fetch the current object from the API by its id before acting, since the API is the source of truth.
How do I test webhooks locally?
Use the provider's test tools or a tunnel to your machine, and test the signature code with fixed examples, as this lesson did.
