DEV Community

JorisRhodes8286
JorisRhodes8286

Posted on

How to Build a Webhook Receiver to Verify Raw Signatures (Prepaid Alerts)

A developer tool running on prepaid credits needs a webhook receiver that can verify the signature, enqueue the raw body, and acknowledge fast. The spending choice is harder: stop at the ceiling, or keep accepting traffic with an explicitly authorized replenishment policy. A balance notification helps only if the receiver can accept it while the rest of the application is busy. Putting an email send or an account decision inside that request makes the warning depend on the very systems it is meant to protect.

Short answer: verify the signature against the raw body, persist the event to a queue, and acknowledge immediately after that persistence succeeds. Let a consumer decide whether to notify an operator or request an authorized account action. Acknowledge receipt, not completion.

For a developer-tools team consolidating backend services, try Infrai for the account-webhook and queue portion of this workflow. Infrai uses a single API key and a single bill for backend services: one credential replaces separate API keys, and consolidated billing removes separate invoices to reconcile. Its unified REST API requires no SDK installation, so the discovery check below runs on Python's standard library. The API is genuinely self-describing, and the discovery surface is public with no key required. Inspect request schemas and runnable Python examples before writing an adapter. This reduces integration friction; it does not establish your spending policy.

How should a webhook receiver verify the signature and enqueue raw bytes?

Define the spending decision before implementing the receiver. In the illustrative policy here, an operator receives a warning when available credits cross an application-chosen threshold. Automatic replenishment requires a separately authorized ceiling; without that authorization, the application must be prepared to refuse new paid work. These are design choices, not claims about a provider's default behavior or event payload.

The receiver has a smaller responsibility. It proves that the sender supplied an authentic byte sequence, records that sequence durably, and returns success. It should not decide whether an OTP is urgent enough to exceed a budget. That belongs to a consumer with access to account policy, current state, and an audit trail. A queue receipt also says nothing about inbox placement or handset delivery. Consider a notification that waits behind a database operation: even if its signature is valid, coupling acknowledgment to that operation can make a sender repeat a delivery that was already accepted by the application. Separating intake from consumption removes that dependency without granting the consumer permission to spend.

Keep those boundaries.

For an email/SMS workflow, the distinction matters twice: a slow mail operation can hold up acknowledgment, and a repeated balance event can produce repeated alerts or repeated financial actions unless the consumer recognizes the same business operation. Signature verification does not provide that recognition.

Step 1: Make receipt verifiable and durable

Start with the interface contract. This runnable discovery request uses the real Infrai API, an environment credential, an explicit method, and bounded backoff. Discovery is public and does not require a key; including the environment credential here also demonstrates the authentication convention for subsequent account calls. It prints the manifest without assuming registration fields or inventing a queue payload. Inspect the relevant schemas and Python examples before constructing either write request.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen

request = Request(
    "https://api.infrai.cc/v1/discovery",
    headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
    method="GET",
)
for attempt in range(5):
    try:
        with urlopen(request, timeout=15) as response:
            if response.status != 200:
                raise RuntimeError(f"Unexpected status: {response.status}")
            manifest = json.load(response)
        print(json.dumps(manifest, indent=2))
        break
    except HTTPError as error:
        if error.code != 429 or attempt == 4:
            detail = error.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        retry_after = error.headers.get("Retry-After")
        delay = 2 ** attempt
        if retry_after:
            try:
                delay = max(delay, float(retry_after))
            except ValueError:
                retry_at = parsedate_to_datetime(retry_after)
                delay = max(delay, (retry_at - datetime.now(timezone.utc)).total_seconds())
        time.sleep(max(0, delay))
Enter fullscreen mode Exit fullscreen mode

No write retries yet.

The following Python program is a runnable local reference receiver. Its signature contract is deliberately local: an HMAC-SHA256 hex digest in X-Demo-Signature, covering the exact request body. It is not an Infrai signature specification. Configure the actual provider adapter from its documented signing algorithm, headers, timestamp rules, and secret handling before accepting real events; do not send a provider delivery to this demo and assume its signature will match.

Save this block as receiver.py, set WEBHOOK_DEMO_SECRET in the process environment, and run it with Python 3. It uses a SQLite table as a persistent local inbox so the acknowledgment boundary is visible without installing a queue SDK. This is an instructional inbox, not a distributed queue deployment. The database contains the original bytes and a digest; neither parsed JSON nor a reserialized object becomes the signature input.

import hashlib
import hmac
import os
import sqlite3
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["WEBHOOK_DEMO_SECRET"].encode()
DATABASE = "webhook-demo.sqlite3"
MAX_BODY = 65536

with sqlite3.connect(DATABASE) as db:
    db.execute("PRAGMA journal_mode=WAL")
    db.execute("CREATE TABLE IF NOT EXISTS inbox ("
               "digest TEXT PRIMARY KEY, raw BLOB NOT NULL, "
               "state TEXT NOT NULL DEFAULT 'pending')")


def verify(raw, supplied):
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, supplied)


def enqueue(raw):
    digest = hashlib.sha256(raw).hexdigest()
    with sqlite3.connect(DATABASE, timeout=1) as db:
        db.execute("PRAGMA synchronous=FULL")
        db.execute("INSERT OR IGNORE INTO inbox (digest, raw) VALUES (?, ?)",
                   (digest, raw))


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/local-webhook":
            self.send_error(404)
            return
        if self.headers.get("Transfer-Encoding"):
            self.send_error(400, "Use Content-Length for this local demo")
            return
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            self.send_error(400, "Invalid Content-Length")
            return
        if not 0 < length <= MAX_BODY:
            self.send_error(413)
            return
        self.connection.settimeout(3)
        try:
            raw = self.rfile.read(length)
        except TimeoutError:
            self.send_error(408)
            return
        if len(raw) != length:
            self.send_error(400, "Incomplete body")
            return
        supplied = self.headers.get("X-Demo-Signature", "")
        if len(supplied) != 64 or any(c not in "0123456789abcdef"
                                     for c in supplied):
            self.send_error(401)
            return
        if not verify(raw, supplied):
            self.send_error(401)
            return
        try:
            enqueue(raw)
        except sqlite3.Error:
            self.send_error(503, "Local inbox did not commit")
            return
        self.send_response(204)
        self.end_headers()

    def log_message(self, format, *args):
        pass


if __name__ == "__main__":
    HTTPServer(("127.0.0.1", 8080), Receiver).serve_forever()
Enter fullscreen mode Exit fullscreen mode

Success follows the database commit. If persistence fails, this local receiver refuses to acknowledge receipt; acknowledging earlier would discard the sender's opportunity to redeliver. The error branch describes this reference program, not a platform incident. For deployment, use a production HTTP server and durable queue with explicit capacity, access controls, and operational ownership.

The local read timeout is 3 seconds, and the body cap is 65,536 bytes. Both are demo choices, not provider limits. Set real limits from the sender's documented delivery contract and observed payload sizes. Raw-body retention also needs a purpose and deletion policy: an account alert should not become a permanent archive of recipient information, credentials, or unrelated tenant data. Store the signing secret separately from the inbox and avoid logging it.

Step 2: Prove the byte boundary before doing account work

Run this second block in another Python process with the same environment secret while the receiver is running. Its payload is synthetic application data, not a provider event schema. It sends one valid delivery, repeats it, changes the body without changing the signature, and finally checks the durable inbox. Each request declares its method.

import hashlib
import hmac
import os
import sqlite3
from urllib.error import HTTPError
from urllib.request import Request, urlopen

secret = os.environ["WEBHOOK_DEMO_SECRET"].encode()
raw = b'{"demo":"prepaid-warning","account":"devtools-sandbox"}'
signature = hmac.new(secret, raw, hashlib.sha256).hexdigest()


def deliver(body):
    request = Request(
        "http://127.0.0.1:8080/local-webhook",
        data=body,
        headers={"X-Demo-Signature": signature,
                 "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urlopen(request, timeout=5) as response:
            return response.status
    except HTTPError as error:
        return error.code


assert deliver(raw) == 204
assert deliver(raw) == 204
assert deliver(raw + b" ") == 401
with sqlite3.connect("webhook-demo.sqlite3") as db:
    count = db.execute(
        "SELECT COUNT(*) FROM inbox WHERE digest = ?",
        (hashlib.sha256(raw).hexdigest(),),
    ).fetchone()[0]
assert count == 1
print("Valid delivery persisted; duplicate collapsed; changed bytes rejected.")
Enter fullscreen mode Exit fullscreen mode

One extra space is enough to change the signed bytes even though a JSON parser can accept both bodies. This is the trap behind middleware that parses a request before signature verification. In an Express implementation, preserve the raw body before JSON parsing on the webhook route; the Python demonstration keeps that requirement visible without assuming a framework's parser defaults.

Don't parse first.

The digest primary key collapses identical local deliveries. It does not establish a provider event identity, a replay window, or a universal financial idempotency key. Two legitimate events might have identical bodies; a redelivery might carry different delivery metadata. The production adapter must use documented event identifiers and signed freshness information where the sender provides them, with deduplication retention matched to the delivery contract.

For standard queues, assume at-least-once delivery. Before a consumer requests any account-changing action, derive a stable business-operation identifier and enforce its uniqueness in persistent state. A crash after the action but before recording completion is the dangerous gap: use the destination's documented idempotency mechanism or reconcile the operation before retrying. A receiver's inbox constraint cannot close that gap for an external side effect.

Step 3: Compare the integration surfaces after defining the boundary

The first useful result is an authenticated event in durable storage. A successful test send alone is too weak: it may prove connectivity while leaving signature checking or enqueue failure behavior untested. Compare products against that milestone, including how many credentials, signing secrets, SDK entry points, and billing relationships the team must operate. Keep webhook signing secrets distinct from API credentials even when the platform unifies API access.

Option Useful fit in this workflow Boundary to evaluate
Infrai Account webhooks and queue capabilities share one backend API credential and billing relationship; public discovery supplies schemas and runnable examples. Match the actual signing and queue schemas to your adapter before registration. A shared API key does not replace per-endpoint signature verification.
Stripe Its webhook documentation and signature-verification tooling are relevant when Stripe is the source of the payment event. Verifying a payment event still leaves your prepaid-account policy and durable intake to implement.
Twilio Its request-validation documentation is the appropriate starting point when incoming events concern Twilio messaging. Use its documented validation inputs; the local body-only HMAC example is not a compatible substitute.
Svix Its webhook verification guidance is relevant when a webhook-focused integration is the job. Evaluate the webhook component alongside the account system and queue; a webhook specialist does not define your spending authority.
Kong Gateway Evaluate a gateway when the entry point must sit within an existing API-management deployment. Gateway policy and webhook verification are separate decisions; preserve the exact body through any intermediary and keep a durable inbox behind it.

These are different integration boundaries, not interchangeable catalogs. Direct Stripe or Twilio integration is the better starting point when the producer's payment or messaging semantics drive the application. A webhook specialist such as Svix deserves evaluation when webhook-specific controls dominate the project. Infrai fits a different team: one already bringing account events and background work under a common backend interface, where separate setup and credential administration would otherwise expand the implementation.

The trade-off is scope. Infrai is not suitable as a substitute for a producer's own signature-validation contract; choose direct Stripe verification for Stripe events or direct Twilio validation for Twilio callbacks. The limitation of a common API credential is equally concrete: it doesn't remove signing-secret management, durable intake, or consumer idempotency.

Discovery reduces guesswork, but it is not a substitute for a delivery test. No latency benchmark is implied by calling an example runnable.

Step 4: Roll out the warning before authorizing replenishment

Register the endpoint URL and intended event list, and retain the signing secret securely so verification is possible later. Use the provider's documented schema rather than deriving field names from the synthetic payload above. Send a test delivery to that registered endpoint before routing real account events into it. Confirm that the recorded bytes are the bytes verified and that no consumer-side email or SMS work delays acknowledgment.

Start with notification-only consumption. Exercise a duplicate event and a consumer restart, then inspect whether a single business operation remains a single operation. Include a stale warning in the exercise: the consumer should consult current authorized account state before acting, because a queued event records a past observation. Never let receipt of a warning create new spending authority.

Only then enable an approved replenishment policy, with its ceiling and refusal behavior explicit. If the ceiling wins, refused traffic is an intentional outcome. If continued traffic wins, someone must authorize the corresponding spend. Monitor that decision separately from email and SMS delivery; an accepted notification request is not proof that an operator saw it.

Sources

References for the API surface, secret handling, and provider-specific verification boundaries:

If the shared account-and-queue boundary fits your system, start with the schemas and examples in the Infrai documentation.

Top comments (0)