Never use Pydantic body parsing on webhook endpoints before signature verification! Both Stripe (Stripe-Signature) and Plaid (Plaid-Verification JWT/SHA-256) compute cryptographic signatures over the exact raw UTF-8 HTTP body bytes.
Here is the production-hardened FastAPI webhook receiver with raw-byte verification, timestamp tolerance, and atomic Redis replay protection:
1. Verify Raw Bytes + Atomic Redis Replay Guard
import stripe
from fastapi import FastAPI, HTTPException, Request
app = FastAPI()
STRIPE_WEBHOOK_SECRET = "whsec_..."
@app.post("/webhooks/stripe")
async def stripe_agent_webhook(request: Request):
# 1. Read exact raw bytes BEFORE any JSON parsing!
raw_body: bytes = await request.body()
sig_header = request.headers.get("stripe-signature")
if not sig_header:
raise HTTPException(status_code=400, detail="Missing Stripe-Signature")
# 2. Verify HMAC + 300-second timestamp tolerance window
try:
event = stripe.Webhook.construct_event(
payload=raw_body,
sig_header=sig_header,
secret=STRIPE_WEBHOOK_SECRET,
tolerance=300, # Reject captured payloads older than 5 minutes!
)
except (ValueError, stripe.error.SignatureVerificationError):
raise HTTPException(status_code=401, detail="Invalid webhook signature")
# 3. Atomic Redis Replay Guard (SET NX EX 86400)
event_id = event["id"]
is_new = await request.app.state.redis.set(
f"webhook:seen:stripe:{event_id}",
"1",
nx=True,
ex=86400, # 24-hour deduplication window
)
if not is_new:
# Return 200 OK cleanly so Stripe stops retrying, without waking the agent!
return {"status": "duplicate_ignored", "event_id": event_id}
# 4. Safe to enqueue reconciliation agent job!
await enqueue_reconciliation_agent(event_id, event["type"], event["data"]["object"])
return {"status": "queued", "event_id": event_id}
Why Every Line Matters:
await request.body(): Preserves exact byte-for-byte payload formatting.
tolerance=300: Prevents attackers from replaying old signed requests days later.
redis.set(..., nx=True, ex=86400): Atomic check-and-set guarantees that even two concurrent duplicate webhook deliveries within the same millisecond will trigger the agent at most once.