Verify HMAC webhook signatures over the exact received bytes, compare in constant time, bound the timestamp, accept rotated secrets and drop replays by id.
The signature that stopped matching
A payment or messaging provider sends webhooks to an endpoint at the fictional Belgavi's Book Store, signed with a shared secret. The integration was tested and worked. Months later, a framework upgrade adds JSON body parsing middleware, and every webhook starts failing verification. Someone "fixes" it by computing the signature over json.dumps(request.json). Now valid webhooks fail intermittently, on any event containing a non-ASCII character, and the team adds a configuration flag to skip verification while they investigate.
Webhook verification fails in a small number of well-understood ways. This guide builds a receiver that avoids all of them: it verifies the exact bytes received, compares in constant time, enforces a timestamp tolerance, accepts more than one secret during rotation, and keeps a replay cache keyed by the message id. The scheme follows the Standard Webhooks specification, whose symmetric signatures are HMAC-SHA256, but the same rules apply to provider-specific schemes.
What is signed
The Standard Webhooks specification signs three things together: the message id, the timestamp of the delivery attempt, and the body, concatenated with full stops. The signature is the base64 of HMAC-SHA256 over that content, sent with a v1, prefix in the webhook-signature header, alongside webhook-id and webhook-timestamp. The header may carry several signatures separated by spaces, which is how a producer signs with an old and a new secret at once.
def sign(secret: bytes, msg_id: str, timestamp: int, body: bytes) -> str:
content = msg_id.encode() + b'.' + str(timestamp).encode() + b'.' + body
return 'v1,' + base64.b64encode(hmac.new(secret, content, hashlib.sha256).digest()).decode()Signing the id and timestamp, not just the body, matters. A signature over the body alone can be replayed forever, and an attacker who captures one delivery can resend it with a fresh timestamp header. The specification also asks that ids and timestamps never contain a full stop, so that the boundaries in the signed content cannot be shifted.
Rule one: verify the bytes you received
HMAC is defined over bytes, as RFC 2104 specifies. The specification is explicit that the payload signed must be exactly the payload sent, and that a common failure is parsing the JSON and serializing it again before verifying. In the companion example the original body is 87 bytes. Python's json.dumps(json.loads(body)) produces 98 bytes: a space after every colon and comma, and the é in "Café edition" written as a é escape. The content is the same JSON value and a different byte string, so verification fails.
The fix is structural. Read the raw request body before any parsing middleware runs, verify it, and only then parse it. Most web frameworks offer a raw-body hook for exactly this; use it on the webhook route only.
Rule two: compare in constant time
The specification requires a constant-time comparison for symmetric signatures, because a comparison that stops at the first differing byte leaks how many leading bytes were right, and an attacker can use the timing to build a valid signature byte by byte. Python provides hmac.compare_digest; Java has MessageDigest.isEqual; most languages have an equivalent. Compare the decoded signature bytes or the full base64 strings, never a prefix.
Rule three: a timestamp tolerance
Reject a delivery whose timestamp is too far from the receiver's clock. The example uses 300 seconds, a common choice. A captured delivery replayed 301 seconds later is rejected before the signature is even computed, which also bounds how long the replay cache below must remember ids. Keep the receiver's clock synchronized; a receiver that drifts by a few minutes rejects everything.
Rule four: a replay cache keyed by the id
The tolerance stops old replays but not a replay within the window. The specification suggests using the webhook-id as an idempotency key. The id stays the same across retries of the same event, so the cache also absorbs the provider's own redeliveries, which are normal: a delivery whose response timed out will be sent again.
Record the id only after the signature verifies, so unauthenticated requests cannot fill the cache, and keep entries for at least the tolerance window, twice it to allow for clock differences. A duplicate should return a success status without reprocessing; returning an error makes the provider retry a delivery you already handled.
if not any(hmac.compare_digest(o.encode(), e.encode()) for o in offered for e in expected):
return 'reject: no matching signature'
if msg_id in self.seen:
return 'duplicate: already processed' # respond 2xx, do nothing
self.seen[msg_id] = self.now()
return 'accept'When several receivers run behind a load balancer, the cache must be shared, for example a key-value store with expiry, or a unique constraint on processed ids in the database that the handler writes in the same transaction as its effects.
Rule five: rotate without downtime
Keep a list of current secrets and accept a signature that matches any of them. During rotation the producer signs with both, or switches at a moment you do not control; either way the receiver accepts both until the old one is retired. In the example, a delivery signed with the old secret is accepted while both are configured, and a body altered after signing fails against both.
The order of checks
The order of the checks is part of the design, not a style choice:
- Reject malformed headers: a missing id, an id containing a full stop, a timestamp that is not an integer.
- Reject a timestamp outside the tolerance. This costs nothing and stops old captures before any cryptography runs.
- Compute the expected signature for every current secret and compare with every offered
v1signature in constant time. - Only now consult the replay cache, and record the id.
- Only now parse the body and hand the event to application code.
Putting the replay cache before the signature check lets anyone poison it with forged ids. Parsing before verifying reintroduces the re-serialization failure and exposes the parser to unauthenticated input. The receiver should also respond quickly: verify, record the id, enqueue the event and return a success status, then do the slow work asynchronously. Providers retry deliveries that time out, and slow handlers turn into duplicate deliveries.
The worked results
The companion example runs seven deliveries through one receiver with two secrets and a fixed clock:
- The raw body: accepted.
- The same id again: duplicate, already processed.
- The parsed and re-serialized body: rejected, no matching signature.
- A delivery signed with the old secret: accepted.
- A body changed from CASE-4301 to CASE-4999 after signing: rejected.
- A capture replayed 301 seconds later: rejected, outside the tolerance.
- An id containing a full stop: rejected as malformed.
A further test sends a header with two signatures, one invalid, and checks that the valid one is accepted, and another checks that the replay cache keeps an id for exactly twice the tolerance.
Failure modes worth testing
- Verification disabled by configuration. A flag that skips verification will eventually be left on. If you need one for local development, make the service refuse to start with it in production.
- Errors that reveal too much. Return the same status for every verification failure; do not say which check failed.
- Processing before verifying. Some handlers enqueue the payload and verify in the worker. Verify at the edge, before anything trusts the body.
- Body size. Read the raw body with a size limit, because verification has to read all of it.
- Asymmetric signatures. The specification also defines
v2asignatures with ed25519, where the receiver holds only a public key. If your provider offers them, prefer them: a leaked receiver configuration then cannot be used to forge webhooks.
Verification
The six tests in the companion example cover every result above. For your own endpoint, keep a fixture of real deliveries with their headers, captured once, and replay them in tests with a frozen clock: one should verify, one with a changed byte should fail, one past the tolerance should fail, and the same one twice should be processed once.
Run the example yourself
The signer, the verifier with tolerance, rotation and replay cache, and six tests. Companion code on GitHub; its README lists the prerequisites, exact commands, expected output and limits.