Skip to content

Lesson 3 of 9 · 25m

Verification and Replay Protection on the Receiver

Implement raw-body HMAC verification, timestamp windows, constant-time comparison, and replay caches without breaking valid retries.

Webhook receivers fail when developers verify the signature after the framework has already normalized, parsed, or discarded the bytes that were signed. They also fail when replay protection is either absent or so naive that legitimate retries are rejected. Your job is not merely to check HMAC. Your job is to bind a fresh, authentic message to a processing pipeline that expects duplicates.

Read the raw body exactly once

In Node.js, JSON middleware often consumes the body before your verifier sees it. Register the webhook route with raw body handling:

app.post("/webhooks/acme", express.raw({ type: "application/json" }), async (req, res) => {
  verifyAcmeSignature(req.body, req.headers);
  const event = JSON.parse(req.body.toString("utf8"));
  await enqueueEvent(event);
  res.sendStatus(202);
});

The order matters. Verify before parsing if your parser is exposed to hostile input, but remember verification itself needs the raw bytes. If a reverse proxy re-encodes the body, the digest will mismatch even though the JSON content is equivalent.

Verification needs constant-time comparison

import hashlib, hmac

def verify(secret: bytes, timestamp: str, body: bytes, presented: str) -> bool:
    signed = timestamp.encode() + b"." + body
    expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, presented)

compare_digest is not superstition. Equality on strings may exit at the first mismatched character in some runtimes. Timing attacks over the internet are noisy, but cryptographic comparisons should not depend on whether an attacker can measure microseconds.

Freshness and replay are different controls

A timestamp window answers "is this message recent?" A replay cache answers "have I already accepted this exact delivery?" You need both:

1. require Acme-Webhook-Timestamp
2. reject timestamps outside +/- 300 seconds
3. verify HMAC over timestamp + body
4. compute replay key: hash(secret_id, timestamp, body or event id)
5. insert key into Redis/DB with a TTL slightly over the retry window
6. reject if the key already exists before processing

Careful: this detects duplicated delivery, but consumers should still process event IDs idempotently. A provider may intentionally resend the same event after an incident with a new timestamp or delivery ID. Replay protection must not become an excuse to ignore idempotent business processing.

Clock skew is operational reality

Consumer clocks drift. NTP outages happen. A five-minute window is common because it balances replay risk and skew. Rejecting at five seconds creates false failures for mobile-adjacent or containerized infrastructure. Record the observed skew distribution; if a customer consistently sits near the edge, fix their time source rather than loosening security globally.

Verification failure behavior matters

Return 401 or 403 for bad signatures and 400 for malformed envelopes. Do not return 200 and silently drop invalid messages; that hides attacks and integration bugs. Also avoid verbose oracle responses like expected digest was.... A generic invalid signature is enough.

Field notes

  • Percent-decoding, charset conversion, or JSON re-serialization before verification changes bytes and produces impossible-to-debug mismatches.
  • Multiple active secrets mean multiple valid verifications; do not accidentally accept one weak or deprecated secret forever.
  • Do not use client IP allowlisting as the primary control. Cloud NATs, egress rotation, and provider migration make it brittle.
  • If the same endpoint receives several providers, choose secrets and parsing logic by explicit route or provider header, never by guessing payload shape.
  • Test replay using a captured signed request after a minute, after five minutes, and after key rotation. Those are different failure paths.

Was this lesson helpful?

Sign in to rate