← Back to FastAPI, page 5

fastapi-0093 · Hard senior

How do you securely receive webhooks in FastAPI: HMAC signature verification over the raw body, timestamp tolerance and replay protection?

Read the raw request bytes before any JSON parsing, compute an HMAC (usually SHA-256) over timestamp plus body with the shared secret, and compare it to the signature header with hmac.compare_digest. Reject timestamps outside a small window (for example five minutes) to limit replay, store processed event IDs to ignore duplicates, return 2xx quickly and process asynchronously, and support secret rotation by accepting several signatures during a transition period.

Full answer

Why verify: a webhook URL is public. Without authentication anyone can post fake events (payment succeeded, user upgraded).

Verification recipe (Stripe-style header t=1733300000,v1=<hex>):

  1. Get the raw body: body = await request.body(). Do not declare a Pydantic body parameter first: parsing and re-serialising JSON changes bytes (spacing, key order, unicode escapes), so the signature would not match.
  2. Parse the header, build the signed payload f"{timestamp}.".encode() + body.
  3. expected = hmac.new(secret, payload, hashlib.sha256).hexdigest().
  4. Compare with hmac.compare_digest(expected, received) (constant time) to avoid timing leaks. Never use ==.
  5. Check the timestamp: abs(now - timestamp) <= 300 seconds. This limits replay of captured requests. Include the timestamp in the signed data, otherwise an attacker can change it.
  6. Parse JSON only after verification, with a Pydantic model.
  7. Deduplicate: providers deliver at least once and retry on non-2xx, so store event.id (unique constraint) and ignore repeats. Make handlers idempotent.
  8. Respond 200 quickly; enqueue slow work (queue or outbox) so the provider does not time out and retry.

Other points:

  • Secret management: one secret per endpoint, stored in a secrets manager; support rotation by trying a list of active secrets and by accepting multiple v1= entries.
  • Use HTTPS only, and optionally IP allow-lists from the provider as an extra layer (not a replacement).
  • Limit body size, and return 400 for bad signatures without revealing which check failed.
  • Log event IDs, not secrets or full bodies containing personal data.
  • Test with fixed timestamps (inject the clock) and a table of cases: valid, wrong secret, altered body, stale timestamp, missing header, duplicate event.
  • For providers that sign with asymmetric keys (GitHub uses HMAC; others use Ed25519 or RSA), verify with their public key and the same raw-body rule.
python
import hashlib
import hmac
import json

from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.testclient import TestClient

SECRET = b"whsec_demo_only"
TOLERANCE = 300
NOW = 1_733_300_000                                  # injected clock so the demo is deterministic
processed: set[str] = set()
app = FastAPI()


def sign(body: bytes, timestamp: int, secret: bytes = SECRET) -> str:
    mac = hmac.new(secret, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    return f"t={timestamp},v1={mac}"


@app.post("/webhooks/payments")
async def webhook(request: Request, x_signature: str = Header(default="")):
    body = await request.body()                       # raw bytes, before any JSON parsing
    try:
        parts = dict(p.split("=", 1) for p in x_signature.split(","))
        timestamp, received = int(parts["t"]), parts["v1"]
    except (KeyError, ValueError):
        raise HTTPException(400, "Invalid signature")
    expected = hmac.new(SECRET, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, received):
        raise HTTPException(400, "Invalid signature")
    if abs(NOW - timestamp) > TOLERANCE:
        raise HTTPException(400, "Stale timestamp")
    event = json.loads(body)
    if event["id"] in processed:                      # at-least-once delivery means duplicates happen
        return {"status": "duplicate ignored"}
    processed.add(event["id"])
    return {"status": "processed", "type": event["type"]}


c = TestClient(app)
body = json.dumps({"id": "evt_1", "type": "payment.succeeded"}, separators=(",", ":")).encode()


def post(b, sig):
    return c.post("/webhooks/payments", content=b, headers={"X-Signature": sig, "Content-Type": "application/json"})


print("valid:", post(body, sign(body, NOW)).json())
print("duplicate:", post(body, sign(body, NOW)).json())
print("tampered body:", post(body.replace(b"succeeded", b"refunded"), sign(body, NOW)).status_code)
print("wrong secret:", post(body, sign(body, NOW, b"other")).status_code)
print("stale timestamp:", post(body, sign(body, NOW - 3600)).json())
print("missing header:", c.post("/webhooks/payments", content=body).status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): valid: {'status': 'processed', 'type': 'payment.succeeded'} duplicate: {'status': 'duplicate ignored'} tampered body: 400 wrong secret: 400 stale timestamp: {'detail': 'Stale timestamp'} missing header: 400

Key points

  • Verify over the raw bytes before JSON parsing
  • Constant-time comparison with hmac.compare_digest
  • Signed timestamp plus tolerance window limits replay
  • Deduplicate by event ID; handlers must be idempotent
  • Respond quickly and process asynchronously; support secret rotation

Common mistakes

  • Parsing JSON first and verifying a re-serialised body
  • Comparing signatures with == instead of compare_digest
  • No timestamp check, which allows replay forever
  • Doing slow work before responding so the provider retries
  • Not deduplicating events

Follow-ups

  • How do you rotate webhook secrets without downtime?
  • How do asymmetric webhook signatures differ?
  • How would you test signature code?

Tips

  • List the verification steps
  • Say raw body first
  • Mention replay and duplicates