download

How do you rotate a webhook HMAC secret with zero downtime?

Security~10 minReviewed 2 Dec 2026Free · No sign-in

Question

Your payment webhook receiver checks X-Signature against one WEBHOOK_SECRET. Last quarter, swapping that secret in a single deploy dropped 400 valid in-flight webhooks with HTTP 401 while senders still signed with the old key.

  1. Update check_sig to accept an ordered key list ([current, previous]) using constant-time comparison.
  2. Give the exact rollout order to rotate from test-key-v1 to test-key-v2 without dropping valid requests.
"CODE · PYTHON"
import hashlib
import hmac


def check_sig(payload, sig_hex, secret):
    expected = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    return expected == sig_hex
Show hints (3)
  1. "TWO ACTIVE KEYS"

    Let the receiver accept signatures produced by either current or previous during the overlap window.

  2. "AVOID TIMING LEAKS"

    Replace == on HMAC digests with hmac.compare_digest so comparison time does not leak matching prefix bytes.

  3. "RECEIVER BEFORE SENDER"

    Which side must know test-key-v2 first so no in-flight webhook hits a receiver that rejects it?

Show checked explanation

Accept an ordered key list [current, previous] on the receiver and compare each digest with hmac.compare_digest. Roll out in four steps: add test-key-v2 to all receivers, switch senders to sign with test-key-v2, wait until metrics show zero traffic on test-key-v1, then remove test-key-v1.

"SOLUTION · PYTHON"
import hashlib
import hmac


def sign(payload, secret):
    return hmac.new(secret, payload, hashlib.sha256).hexdigest()


def check_sig(payload, sig_hex, secrets):
    matched = False
    for key in secrets:
        matched |= hmac.compare_digest(sign(payload, key), sig_hex)
    return matched


body = b'{"invoice":"invoice_9001"}'
ring = [b"test-key-v2", b"test-key-v1"]
cases = [("v2", b"test-key-v2"), ("v1", b"test-key-v1"), ("bad", b"wrong")]
for label, key in cases:
    print(label, "->", check_sig(body, sign(body, key), ring))
"OUTPUT"
v2 -> True
v1 -> True
bad -> False

Code run on CPython 3.12.10 against synthetic HMAC-SHA256 signatures across all four rotation stages; official Python, OWASP, AWS, and NIST links checked. Checked by an editor other than the author.

Walkthrough

A single-key swap fails because rolling deploys, worker queues, and webhook retries mean senders and receivers never cut over at the same instant. Zero-downtime rotation separates adding the new secret from retiring the old secret with a dual-key accept window.

stagesenders sign withreceivers acceptexit check
1. Add new keytest-key-v1[test-key-v2, test-key-v1]Every receiver pod loaded v2
2. Switch signertest-key-v2[test-key-v2, test-key-v1]New events sign with v2; retries still pass on v1
3. Drain old traffictest-key-v2[test-key-v2, test-key-v1]Metrics show 0 accepted calls on v1 past retry TTL
4. Retire old keytest-key-v2[test-key-v2]Delete v1 from config and secret manager

Use constant-time digest comparison. Python's == stops at the first mismatching character, which leaks timing signals across repeated requests. hmac.compare_digest checks the full digest in constant time. Combining loop results with |= also inspects every key in the tiny ring instead of stopping early when the first key matches.

Track key drain safely. Tag each key with a non-secret key ID (v1, v2) and increment a counter (webhook_sig_match{key_id="v1"}) whenever a signature matches. Never log raw secrets or full digests. Once v1 hits zero for longer than your maximum webhook retry window, stage 4 can retire v1 cleanly.

Common mistakes

  • Switching senders to test-key-v2 before every receiver instance accepts it. Lagging pods and rolling deploys reject valid webhooks with 401.
  • Comparing HMAC hex strings with == instead of hmac.compare_digest. Early exit on the first wrong character creates a timing side channel.
  • Leaving test-key-v1 in the accept list forever "just in case". Rotation limits exposure only after the old key is actually removed.
  • Logging the raw secret or signature header to debug a 401 spike. Emit only the non-secret key_id and pass/fail count.

Follow-up questions

  • "What changes during an emergency rotation after test-key-v1 is confirmed leaked?" Trade zero downtime for fast containment. Deploy test-key-v2 to receivers, switch senders right away, and revoke test-key-v1 immediately rather than waiting out the retry window, then replay any dropped events later.
  • "How do you stop someone from replaying a valid signed webhook hours later?" Include a Unix timestamp header (and event ID) inside the signed payload, such as f"{ts}.{body}". Reject requests outside a short clock skew window like 5 minutes, and deduplicate event IDs.
  • "How does zero-downtime rotation work for asymmetric JWT signing keys (RS256 or EdDSA)?" Use the same overlap order. Publish the new public key under a new kid in your JWKS endpoint and wait past cache TTL. Then switch issuers to the new private key, wait past token expiry, and drop the old public key.

What a strong answer covers

Implements a [current, previous] accept window using hmac.compare_digest, gives the exact four-stage rollout order, tracks old-key drain with non-secret key IDs, and distinguishes routine rotation from emergency revocation.

Open in interactive practice deck →

Original OfferVibe question. Python hmac.compare_digest · OWASP Secrets Management Cheat Sheet · AWS Secrets Manager Rotation · NIST SP 800-57 Part 1 Rev. 5.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.