Most webhook verification handlers look fine in unit tests and fail quietly on their first real traffic spike. You pass a sample JSON payload through TestClient, check the 200 OK, and ship it. A week later a payment provider retries a slow callback twice, or a reverse proxy changes JSON whitespace, and either valid webhooks start returning 401 or the same order gets fulfilled twice.
We ran into several of these exact edge cases while hardening webhook and checkout handlers in a small open Telegram Mini App backend (https://github.com/angeldev-tech/ton-alpha-tma). None of them required exotic cryptography to fix, but every one of them slipped past a basic happy-path test.
Here are four concrete bugs that show up regularly in Python and FastAPI webhook receivers, along with runnable code to avoid them.
1. Hashing re-serialized JSON instead of raw request bytes
The most common FastAPI mistake is accepting a Pydantic model in the route signature and then re-dumping it to JSON to verify the HMAC signature.
# Broken: do not verify HMAC against re-serialized Pydantic data
@app.post("/webhooks/broken")
async def broken_webhook(payload: dict, x_signature: str = Header(...)):
raw = json.dumps(payload).encode("utf-8") # key order and whitespace drift
...
When FastAPI parses JSON into a dict or Pydantic model and you call json.dumps(), you lose the exact byte sequence the sender signed. Python's default json.dumps() inserts spaces after commas and colons, reorders keys when sort_keys=True is set, and normalizes floats like 10.00 to 10.0. Local tests pass only because the test helper uses json.dumps() with the same defaults.
Always read the exact bytes from await request.body() before parsing JSON, and cap body size early so a caller cannot force your worker to buffer a huge payload before signature checks run.
2. Comparing digests with == and forgetting header normalization
Comparing hex strings with expected == provided leaks timing information across byte boundaries. Use hmac.compare_digest() from the standard library so the comparison runs in constant time.
Senders also format signature headers inconsistently. GitHub sends sha256=<hex>, some gateways send uppercase hex, and missing headers should fail closed with 401 rather than raising an unhandled AttributeError or 422. Strip any expected prefix and lowercase the hex digest before calling hmac.compare_digest().
3. Signing only the body without a replay window
Checking HMAC(secret, raw_body) proves the payload came from someone holding the shared secret, but it does not stop a replay attack. If an attacker captures one valid signed request from a log aggregator or proxy trace, they can POST the same headers and body again twenty minutes later and trigger your business logic a second time.
The standard pattern (used by Stripe, Slack, and Svix) is to sign both a Unix timestamp header and the raw body bytes together, separated by a dot: f"{timestamp}.".encode("utf-8") + raw_body. On the receiver side, parse the integer timestamp and enforce a tight tolerance window in both directions, such as plus or minus 300 seconds. Rejecting far-future timestamps matters too, otherwise an attacker with a pre-signed future payload or a broken sender clock bypasses expiry checks.
4. Checking duplicates with SELECT before INSERT
Even with valid HMAC verification and a 5-minute replay window, legitimate providers retry webhooks whenever your server takes more than a few seconds to respond. If two identical deliveries arrive at the same millisecond, a naive check-then-act handler fails under concurrency:
# Broken under concurrent retries: two workers both see row = None
row = conn.execute("SELECT 1 FROM webhook_events WHERE event_id = ?", (event_id,)).fetchone()
if row is None:
fulfill_order(payload)
conn.execute("INSERT INTO webhook_events (event_id) VALUES (?)", (event_id,))
Both requests pass row is None, both run fulfill_order(), and then one fails on insert or both insert duplicate rows if there is no unique constraint.
Fix this at the database layer. Put a PRIMARY KEY or UNIQUE constraint on event_id and claim the event atomically inside the same database transaction as your state transition. In SQLite, use INSERT OR IGNORE; in PostgreSQL, use INSERT INTO webhook_events (event_id, received_at) VALUES (%s, %s) ON CONFLICT (event_id) DO NOTHING RETURNING event_id. If zero rows were inserted, you already processed that event. Return 200 OK immediately so the provider marks delivery complete and stops retrying.
Runnable FastAPI implementation
Below is a minimal FastAPI receiver combining all four guards using only the Python standard library, FastAPI, and SQLite.
import hashlib
import hmac
import json
import sqlite3
import time
from typing import Optional
from fastapi import FastAPI, Header, HTTPException, Request
WEBHOOK_SECRET = b"whsec_replace_with_env_secret"
MAX_BODY_BYTES = 256 * 1024
REPLAY_WINDOW_SECONDS = 300
app = FastAPI()
def init_db(conn: sqlite3.Connection) -> None:
conn.execute(
"""
CREATE TABLE IF NOT EXISTS webhook_events (
event_id TEXT PRIMARY KEY,
event_type TEXT NOT NULL,
received_at INTEGER NOT NULL
)
"""
)
conn.commit()
db_conn = sqlite3.connect(":memory:", check_same_thread=False)
init_db(db_conn)
def compute_signature(secret: bytes, timestamp: str, raw_body: bytes) -> str:
signed_payload = f"{timestamp}.".encode("utf-8") + raw_body
return hmac.new(secret, signed_payload, hashlib.sha256).hexdigest()
def verify_webhook(
raw_body: bytes,
signature_header: Optional[str],
timestamp_header: Optional[str],
now: Optional[int] = None,
) -> None:
if not signature_header or not timestamp_header:
raise HTTPException(status_code=401, detail="Missing webhook auth headers")
try:
ts = int(timestamp_header)
except ValueError:
raise HTTPException(status_code=401, detail="Malformed webhook timestamp")
current_ts = int(time.time()) if now is None else now
if abs(current_ts - ts) > REPLAY_WINDOW_SECONDS:
raise HTTPException(status_code=401, detail="Webhook timestamp outside replay window")
provided = signature_header.strip()
if provided.startswith("sha256="):
provided = provided[len("sha256=") :]
provided = provided.lower()
expected = compute_signature(WEBHOOK_SECRET, timestamp_header, raw_body)
if not hmac.compare_digest(expected, provided):
raise HTTPException(status_code=401, detail="Invalid webhook signature")
def claim_event(conn: sqlite3.Connection, event_id: str, event_type: str, now_ts: int) -> bool:
# Atomic deduplication: returns True only on the first delivery.
# For PostgreSQL, use:
# INSERT INTO webhook_events (event_id, event_type, received_at)
# VALUES (%s, %s, %s) ON CONFLICT (event_id) DO NOTHING
cur = conn.execute(
"""
INSERT OR IGNORE INTO webhook_events (event_id, event_type, received_at)
VALUES (?, ?, ?)
""",
(event_id, event_type, now_ts),
)
conn.commit()
return cur.rowcount == 1
@app.post("/webhooks/events")
async def receive_webhook(
request: Request,
x_webhook_signature: Optional[str] = Header(default=None),
x_webhook_timestamp: Optional[str] = Header(default=None),
):
raw_body = await request.body()
if len(raw_body) > MAX_BODY_BYTES:
raise HTTPException(status_code=413, detail="Payload too large")
verify_webhook(raw_body, x_webhook_signature, x_webhook_timestamp)
try:
event = json.loads(raw_body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
event_id = event.get("id")
event_type = event.get("type")
if not isinstance(event_id, str) or not isinstance(event_type, str):
raise HTTPException(status_code=400, detail="Missing event id or type")
is_first_delivery = claim_event(db_conn, event_id, event_type, int(time.time()))
if not is_first_delivery:
return {"status": "duplicate_ignored", "event_id": event_id}
# Run domain state update in the same transaction or enqueue to a durable worker.
return {"status": "processed", "event_id": event_id}
Testing the failure modes, not just the happy path
A useful webhook test suite should assert all four failure cases directly against raw byte strings with irregular spacing:
from fastapi.testclient import TestClient
client = TestClient(app)
def post_signed(raw_body: bytes, ts: int, tamper_sig: bool = False):
sig = compute_signature(WEBHOOK_SECRET, str(ts), raw_body)
if tamper_sig:
sig = "0" * 64
return client.post(
"/webhooks/events",
content=raw_body,
headers={
"Content-Type": "application/json",
"X-Webhook-Timestamp": str(ts),
"X-Webhook-Signature": f"sha256={sig}",
},
)
now = int(time.time())
# Notice compact formatting with no spaces after colons or commas
body = b'{"id":"evt_101","type":"invoice.paid","amount":1999}'
assert post_signed(body, now).json()["status"] == "processed"
assert post_signed(body, now).json()["status"] == "duplicate_ignored"
assert post_signed(body, now - 600).status_code == 401
assert post_signed(body, now, tamper_sig=True).status_code == 401
If your handler ever calls an external API before finishing work, keep the database transaction short: insert the verified raw event into an inbox table with ON CONFLICT DO NOTHING, return 200 OK, and let a background worker process the row idempotently.
How do you handle webhook deduplication when downstream processing fails halfway through after you have already recorded event_id? Do you track a status state machine on the inbox table (received, processed, failed), or let the upstream provider retry by rolling back the claim?
Top comments (0)