Webhook Signatures: Verify Raw Bytes and Handle Replays
Separate webhook HMAC verification, timestamp checks and durable duplicate handling. Includes tested Python and SQLite examples with explicit limits.
Verify the provider’s exact signing input before parsing or processing a webhook. Authentication alone does not establish freshness or prevent duplicate effects. Use authenticated timestamps where supported, durable event identity and recoverable processing state; follow the provider SDK for its actual signature format.
Three questions a receiver must answer
A webhook signature can be valid while a repeated request still causes an unwanted second action. It can also be invalid even though the JSON looks identical to the sender’s example. Both situations follow from treating authentication, freshness and business processing as one check. Give each responsibility its own decision and evidence.
Authentication asks whether the delivered bytes match the signing contract under a trusted key. Freshness asks whether an authenticated delivery falls within the allowed time policy, when the contract supports that check. Idempotency asks whether processing this event again would repeat an effect. Passing one does not imply passing the others.
This guide builds a small verification and inbox laboratory, not an HTTP server. Its signing format is explicitly invented for learning. Use a provider’s maintained SDK and documented contract for a real integration. Nothing here changes Prep With Proof’s checkout or production webhook handlers.
| Decision | Useful evidence | What it does not prove |
|---|---|---|
| Signature matches | Expected HMAC over the specified bytes | That this delivery is new |
| Signed time is acceptable | Authenticated timestamp and server clock | That it has not arrived twice inside the window |
| Event stored once | Durable unique key and processing state | Exactly-once effects in an external system |
Read the provider contract before touching the body
GitHub documents HMAC-SHA256 in X-Hub-Signature-256, with a sha256= prefix, computed from the webhook secret and payload. Its delivery identifier is a separate header. Do not assume that every header you can read is covered by the payload signature. When designing your own format, explicitly bind the identity and timestamp that your replay policy relies on.
Stripe’s webhook handling uses a different signature format and its verification guidance requires the unmodified request body. An endpoint signing secret is not interchangeable with an API credential or another endpoint’s secret. The appropriate provider helper should receive the original body and the corresponding signature header. Copying a GitHub verifier into a Stripe endpoint is not an adaptation of the same protocol.
Write down the algorithm, exact signing input, header grammar, timestamp behavior, key scope and rotation procedure. Check whether a timestamp represents the event’s creation or a delivery attempt. If the sender has no signed freshness value, adding an unsigned date header at the receiver does not create replay protection.
Preserve bytes before parsing JSON
Reading a request into a JSON object and serializing it again can change whitespace, ordering, escaping or numeric representation. The resulting document may mean the same thing to the application while having a different byte sequence. Compute the signature over the contract’s input, not over a convenient reconstruction.
At the HTTP adapter, enforce a request-size limit before buffering. Obtain the raw body before middleware replaces it, and avoid decoding and re-encoding it for verification. Decide explicitly how content encoding is handled by the provider and framework. A valid signature cannot compensate for an upstream component verifying one representation while a downstream component processes another.
After verification, parse and validate the application schema. Restrict accepted event types and actions, validate expected account or tenant scope, and authorize the requested state change. A genuine event can still be unsupported or irrelevant to this endpoint. The parser and business rules remain necessary even after cryptographic authentication succeeds.
A bounded demonstration verifier
Save this as verifier.py. The demonstration signs DOMAIN + timestamp + a dot + event_id + a dot + raw body, where DOMAIN is the fixed prefix shown in the code. Timestamp and event ID allow only the displayed ASCII grammars, so the dot separators are unambiguous. A real provider will have its own signing input and may not use this construction.
The receiver allows an absolute clock difference of at most 300 seconds, including a limited future skew. That value is a teaching policy, not a universal webhook requirement. The clock is injected as now so tests are deterministic; an HTTP integration must supply its own current trusted server time, never a client-provided substitute.
Keys are passed from trusted server configuration as a small tuple of active byte strings. The function checks their presence, validates the bounded signature syntax, then compares HMAC values with compare_digest. It does not prove that a configured key has adequate entropy; generate production keys securely and never use the fixture’s public test key.
import hashlib
import hmac
import re
DOMAIN = b"demo-reports-v1."
MAX_BODY = 1024 * 1024
def verify(raw, timestamp, event_id, signature, secrets, *, now):
"""Demo contract only; not a GitHub or Stripe verifier."""
if not secrets or any(not isinstance(k, bytes) or not k for k in secrets):
raise ValueError("configure nonempty signing keys")
if not isinstance(raw, bytes) or len(raw) > MAX_BODY:
return False
if not all(isinstance(x, str) for x in (timestamp, event_id, signature)):
return False
if not re.fullmatch(r"[0-9]{1,12}", timestamp):
return False
if not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", event_id):
return False
if not re.fullmatch(r"sha256=[0-9a-f]{64}", signature):
return False
if abs(now - int(timestamp)) > 300:
return False
message = (DOMAIN + timestamp.encode("ascii") + b"."
+ event_id.encode("ascii") + b"." + raw)
matched = False
for key in secrets: # bounded active keys supplied by the server
expected = "sha256=" + hmac.new(key, message, hashlib.sha256).hexdigest()
matched = hmac.compare_digest(expected, signature) or matched
return matched
Source: Python hmac and compare_digest ↗
A time window still permits repeated deliveries
An intercepted valid request can be resent during the allowed window. A legitimate sender can also retry because it lost the response after your server committed work. The receiver cannot decide which happened merely by observing the second arrival. It needs a stable authenticated event identity and a durable decision about that identity.
GitHub’s best-practice guidance recommends using X-GitHub-Delivery and notes that requested redeliveries retain the original value. That is operationally useful, but the payload HMAC described earlier does not itself bind that header. Evaluate the sender’s complete trust model. Do not describe a cache of unbound identifiers as a general cryptographic replay defense.
In this invented protocol, event_id is part of the HMAC input. Changing it without knowing the key invalidates the signature. The receiver still needs a uniqueness store: an in-memory set disappears on restart and differs across replicas. Namespace the stored identifier by provider and endpoint or tenant when using a shared production inbox.
Source: GitHub: webhook best practices and delivery identifiers ↗
Persist accepted work before acknowledging it
Save the next block as inbox.py. It is a single-namespace SQLite teaching inbox. Initialize it once, then call persist_verified only after the request passes verification, freshness and application validation. The primary key arbitrates concurrent attempts; checking existence in application code and inserting later would introduce a race.
A new event is stored with its original bytes and a pending state in the same transaction as its unique identity. A matching duplicate returns duplicate. Reusing the same identity with different bytes raises an error instead of overwriting the accepted event. This example deliberately treats even a whitespace change as a conflict; adapt that policy only with an explicit event contract.
The function reports acceptance after the transaction commits. A database error is a failure to persist, not a reason to send an optimistic success. The code does not implement an HTTP response policy, schema validator or worker. Protect the database path and stored payload, plan retention and backups, and use an appropriate shared durable store for multiple application hosts.
import hashlib
import sqlite3
def initialize(path):
db = sqlite3.connect(path)
try:
db.execute("""CREATE TABLE IF NOT EXISTS inbox (
event_id TEXT PRIMARY KEY,
body_hash TEXT NOT NULL,
payload BLOB NOT NULL,
state TEXT NOT NULL DEFAULT 'pending'
)""")
db.commit()
finally:
db.close()
def persist_verified(path, event_id, raw):
# Call only after signature, freshness and application-schema checks.
digest = hashlib.sha256(raw).hexdigest()
db = sqlite3.connect(path, timeout=2.0)
try:
with db:
inserted = db.execute(
"INSERT INTO inbox(event_id, body_hash, payload) VALUES (?, ?, ?) "
"ON CONFLICT(event_id) DO NOTHING", (event_id, digest, raw))
if inserted.rowcount == 1:
result = "accepted"
else:
previous = db.execute(
"SELECT body_hash FROM inbox WHERE event_id = ?",
(event_id,)).fetchone()[0]
if previous != digest:
raise ValueError("same event ID with different payload")
result = "duplicate"
return result # transaction committed before acceptance is reported
finally:
db.close()
Run a fixture that proves both gates
Save this third block as fixture.py beside the two modules and run python3 fixture.py without Python optimization flags. It uses a public synthetic key and a temporary database. The expected output is “Fixture passed.” The extra trailing space demonstrates a byte-level signature mismatch; moving the receiver clock beyond the window demonstrates a freshness rejection.
The body is a known literal fixture, so the test treats its schema as already established. An HTTP application must implement actual JSON parsing and schema checks before calling persist_verified. Do not wire the storage helper directly to unverified public input just because the short test can call it directly.
We ran this exact fixture and additional local rejection, rotation, persistence and concurrency cases. These tests exercise the demonstration contract and SQLite inbox. They are not evidence of compatibility with GitHub or Stripe, real delivery behavior, production throughput or downstream exactly-once processing.
import hashlib
import hmac
import tempfile
from pathlib import Path
from verifier import DOMAIN, verify
from inbox import initialize, persist_verified
key = b"synthetic-test-key-not-for-production"
raw = b'{"type":"report.ready","report_id":"r-42"}'
timestamp, event_id, now = "1800000000", "evt_42", 1800000000
message = DOMAIN + timestamp.encode() + b"." + event_id.encode() + b"." + raw
signature = "sha256=" + hmac.new(key, message, hashlib.sha256).hexdigest()
assert verify(raw, timestamp, event_id, signature, (key,), now=now)
assert not verify(raw + b" ", timestamp, event_id, signature, (key,), now=now)
assert not verify(raw, timestamp, event_id, signature, (key,), now=now + 301)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "inbox.db"
initialize(path)
# For this fixture the literal body above is the known application schema.
assert persist_verified(path, event_id, raw) == "accepted"
assert persist_verified(path, event_id, raw) == "duplicate"
print("Fixture passed")
The inbox is the beginning of processing
A worker can discover pending rows and process them after the request ends. However, marking a row complete and calling an external API are two operations. A crash between them can leave uncertainty. Make the downstream operation idempotent with a stable key where supported, or use a recoverable workflow and reconcile the result. A unique inbox row alone does not make remote effects exactly once.
Define retryable failures, terminal failures and manual recovery. Track attempts and the last failure without exposing secrets or full sensitive payloads in logs. Preserve enough state to distinguish work that was accepted from work that was completed. Do not suppress a retry solely because an event is “seen” if its original work has been lost.
Ordering is another separate concern. Distinct authenticated events may arrive out of order. Decide whether the worker should fetch current source state, compare an authoritative version or apply another provider-supported rule. Timestamp validation for transport freshness is not a substitute for business ordering.
Diagnose failures without weakening verification
For a signature mismatch, compare the configured endpoint and environment first, then the algorithm, prefix, raw-body capture and middleware transformations. Use a synthetic signed fixture to reproduce the path. Do not log signing keys, complete signature headers or private request bodies just to make comparison easier.
For freshness failures, check clock synchronization and the provider’s definition of signed time. For duplicate spikes, compare sender retries with receiver latency and persistence failures. For same-ID conflicts, quarantine and investigate the changed bytes or identity scope instead of replacing the stored payload.
Rotate keys with a bounded overlap window tied to the sender’s rollout and documented retry behavior. Remove old keys when that policy ends; an indefinitely accepted old key is not retired. Keep HTTPS and certificate verification enabled. IP rules can be an additional restriction, but they do not replace the message authentication contract.
Evidence for a receiver you can operate
A useful release test sends a valid event, a changed body, a changed signed identity, an expired timestamp and simultaneous duplicate deliveries. It then restarts the receiver and confirms that accepted work survives and duplicate handling remains stable. Include a downstream crash-recovery scenario before claiming an end-to-end delivery guarantee.
The related HTTP retry guide explains why senders repeat requests, while the n8n guide introduces workflow identity. For a secure receiver, preserve those operational lessons alongside exact byte verification, authenticated freshness where available and durable processing state. Each check should have a defined failure path and a test that demonstrates it.
Your next steps
- Raw-body verification, freshness and idempotent processing answer different questions.
- Bind security-relevant fields in the signing contract; do not assume arbitrary headers are signed.
- Persist accepted work and plan downstream crash recovery before claiming delivery guarantees.
Sources & official resources
Linked resources checked on 2026-10-25. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →