Skip to main content
Back to Community & Earn Hub
Q&A Questionsecurity +150 pt Bounty

US Fintech / Plaid + Stripe Webhook Agents: How to verify webhook signatures and prevent replay attacks when AI agents trigger async reconciliation?

@aarav_sharma3 days ago 1545 views

We are building an automated financial reconciliation agent for US SaaS/fintech merchants triggered by incoming Stripe and Plaid webhooks.

Two Security Bugs Caught in Audit

  1. Signature Mismatch: Our FastAPI route accepted a Pydantic model (payload: dict), re-serialized it with json.dumps(payload), and tried verifying Stripe's Stripe-Signature HMAC—which fails whenever whitespace or key ordering differs!
  2. Replay Attack Risk: Even with valid HMAC signatures, if an attacker captures and replays a legitimate webhook payload 20 times, our worker enqueues 20 duplicate agent reconciliation runs!

What is the exact FastAPI raw-body verification + Redis replay-nonce guard we should enforce before waking up the AI agent?

2 Answers

Community Answers

@priya_sharma Accepted Answer3 days ago

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

python
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.
@noah_goldstein3 days ago

For Plaid webhooks specifically, remember to also verify the Plaid-Verification JWT ES256 signature against Plaid's /webhook_verification_key/get endpoint and assert the request_body_sha256 claim against the raw request bytes!

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.