All articles
securityhmacwebhooksidempotency

Rotate Your Webhook Signing Secret With Zero Downtime (HMAC-SHA256)

KestrelMQ signs every outbound webhook attempt with both the new and the old secret during a grace window. Rotate with one API call, prove it with openssl and curl, and verify safely in Node.js and Python.

KestrelMQ Engineering9 min read

A signing secret leaks: a log line, a departing engineer, a compliance deadline. The hard part of rotating it is the cutover. If the sender switches secrets before every receiver replica has the new one, in-flight deliveries fail verification.

KestrelMQ removes the cutover. When you rotate, it keeps the old secret for a grace window and signs every attempt with both secrets, so a receiver holding either one verifies the request. No coordinated deploy, no maintenance window, no 503.

Rotate in one call

Rotation is POST /v1/workspaces/:id/rotate-secret (workspace OWNER or ADMIN):

terminal
export KMQ=http://localhost:3000

curl -s -X POST "$KMQ/v1/workspaces/$WORKSPACE_ID/rotate-secret" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"gracePeriodHours": 24}' | jq
response
{
  "id": "6f0c1d4e-5a52-4b6e-9c0e-2f6a1f3c9a10",
  "webhookSigningSecret": "whsec_9f2c...64 hex characters...",
  "previousSigningSecretExpiresAt": "2026-12-02T10:15:00.000Z",
  "updatedAt": "2026-12-01T10:15:00.000Z"
}
  • gracePeriodHours defaults to SECRET_ROTATION_GRACE_HOURS (24) and accepts 0 to 720. Pass 0 to invalidate the old secret immediately.
  • Until previousSigningSecretExpiresAt, each attempt is signed at send time with both secrets, including retries of deliveries created before the rotation.
  • When the window closes, the header drops back to a single v1=<new_hex>.

During the window the signature header carries two comma-separated entries:

headers
X-KestrelMQ-Timestamp: 1764583000
X-KestrelMQ-Signature: v1=<new_hex>,v1=<old_hex>

Prove it against your own receiver

You do not have to trust the claim. This script signs a test body with the old and the new secret exactly the way the worker does (HMAC_SHA256(secret, "{timestamp}.{rawBody}"), hex, v1= prefix) and sends three requests to your endpoint:

rotation-check.sh
RECEIVER=http://localhost:4000/webhooks/kestrelmq
OLD_SECRET='whsec_old...'   # the secret you had before rotating
NEW_SECRET='whsec_new...'   # webhookSigningSecret from the rotate response

TS=$(date +%s)
BODY='{"event":"order.paid","payload":{"orderId":"ord_9001"}}'

sign() { printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac "$1" -hex | awk '{print $NF}'; }
send() {
  curl -s -o /dev/null -w "$1 -> HTTP %{http_code}\n" -X POST "$RECEIVER" \
    -H 'Content-Type: application/json' \
    -H "X-KestrelMQ-Delivery-Id: test-$RANDOM" \
    -H "X-KestrelMQ-Timestamp: $TS" \
    -H "X-KestrelMQ-Signature: $2" \
    --data-raw "$BODY"
}

OLD_SIG="v1=$(sign "$OLD_SECRET")"
NEW_SIG="v1=$(sign "$NEW_SECRET")"

send "grace window, receiver trusts old"  "$NEW_SIG,$OLD_SIG"   # expect 200 with either secret deployed
send "after window, new secret only"      "$NEW_SIG"             # expect 200 once the new secret is deployed
send "tampered signature"                 "v1=$(printf '0%.0s' {1..64})"   # expect 401

Run it once before you deploy the new secret and once after. The first request must return 200 both times, which is the zero-downtime property. The last must return 401 both times.

The procedure

  1. Rotate. Call the endpoint above and store the new webhookSigningSecret in your secret manager. Requests keep verifying through the v1=<old_hex> entry.
  2. Deploy the new secret at your own pace, either replacing the old one or temporarily listing both (KESTRELMQ_SIGNING_SECRETS=whsec_new...,whsec_old...).
  3. Finish inside the window. 24 hours is far longer than the retry curve (10s, 1m, 5m, 30m: about 36 minutes of backoff across five attempts). For a slower rollout, pass a larger gracePeriodHours (up to 720).
  4. Let the window close, then remove the old secret from your receiver.

If the old secret was leaked and must die now, rotate with gracePeriodHours: 0. KestrelMQ then signs with the new secret only, so deploy it first. If you cannot, return 503 for mismatches while you catch up: a 401 is a fatal 4xx and moves the delivery to FAILED, while a 503 is retried. Anything that did fail can be replayed with POST /v1/deliveries/:id/replay.

Remove the old secret

A receiver that accepts the old secret forever defeats the rotation. Put the removal date in the same ticket that starts it.

What KestrelMQ signs

signing
signed_payload = "${timestamp}.${rawBody}"
signature      = "v1=" + hex(HMAC_SHA256(signing_secret, signed_payload))
HeaderValue
X-KestrelMQ-TimestampUnix seconds at signing time
X-KestrelMQ-Signaturev1=<64 hex chars>; during a grace window v1=<new_hex>,v1=<old_hex>
X-KestrelMQ-Delivery-Iddelivery.id, identical on every retry and replay
X-KestrelMQ-Event-Idevent.id, shared by all deliveries fanned out from one event

The key is the workspace webhookSigningSecret (whsec_ followed by 64 hex characters), returned when you create the workspace. The whole string is the HMAC key, prefix included. Signing happens per attempt: a retry carries a fresh timestamp and signature, so a retry five minutes later is not stale.

Five rules of correct verification

  1. Use the raw bytes. Parse JSON only after the signature checks out.
  2. Enforce a timestamp window. Reject requests more than 300 seconds from your clock, in either direction.
  3. Compare in constant time. crypto.timingSafeEqual (Node.js) or hmac.compare_digest (Python), never ===.
  4. Validate before comparing. timingSafeEqual throws on length mismatch, so check the v1= prefix and the 64-character hex shape first.
  5. Check every v1= entry. Split on , and accept if any matches. A verifier that reads only the first entry breaks the moment you rotate.

TypeScript verifier

Takes a list of secrets, so the same code works before, during and after a rotation. It signs over the timestamp string exactly as received, not a re-formatted number.

verify-kestrelmq.ts
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SEC = 300;
const TIMESTAMP = /^\d{1,12}$/;
const HEX_64 = /^[0-9a-f]{64}$/i;

export function verifyKestrelMQ(
  rawBody: Buffer,
  timestampHeader: string | null | undefined,
  signatureHeader: string | null | undefined,
  secrets: readonly string[],
  toleranceSec = TOLERANCE_SEC,
): boolean {
  if (!timestampHeader || !signatureHeader || !TIMESTAMP.test(timestampHeader)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestampHeader)) > toleranceSec) {
    return false; // replay or clock skew
  }

  // During a rotation grace window the header is "v1=<new>,v1=<old>".
  const provided = signatureHeader
    .split(",")
    .map((part) => part.trim())
    .filter((part) => part.startsWith("v1=") && HEX_64.test(part.slice(3)))
    .map((part) => Buffer.from(part.slice(3), "hex"));
  if (provided.length === 0) return false;

  // Check every secret against every signature; no early exit.
  let ok = false;
  for (const secret of secrets) {
    const expected = createHmac("sha256", secret)
      .update(`${timestampHeader}.`, "utf8")
      .update(rawBody)
      .digest();
    for (const candidate of provided) {
      if (timingSafeEqual(candidate, expected)) ok = true;
    }
  }
  return ok;
}

Express

express.raw keeps the bytes the JSON parser would discard:

server.ts
import express from "express";
import { verifyKestrelMQ } from "./verify-kestrelmq";

const app = express();
const SECRETS = (process.env.KESTRELMQ_SIGNING_SECRETS ?? "")
  .split(",")
  .map((s) => s.trim())
  .filter(Boolean);

app.post(
  "/webhooks/kestrelmq",
  express.raw({ type: "application/json", limit: "1mb" }), // req.body is a Buffer
  async (req, res) => {
    const ok = verifyKestrelMQ(
      req.body as Buffer,
      req.header("x-kestrelmq-timestamp"),
      req.header("x-kestrelmq-signature"),
      SECRETS,
    );
    if (!ok) return res.status(401).send("invalid signature");

    const deliveryId = req.header("x-kestrelmq-delivery-id");
    if (!deliveryId) return res.status(400).send("missing delivery id");
    if (await alreadyProcessed(deliveryId)) return res.sendStatus(200);

    await enqueueForProcessing(deliveryId, JSON.parse((req.body as Buffer).toString("utf8")));
    res.sendStatus(200); // respond fast, work async
  },
);

Next.js (App Router)

arrayBuffer() returns the unmodified bytes:

app/api/webhooks/kestrelmq/route.ts
import { NextResponse } from "next/server";
import { verifyKestrelMQ } from "@/lib/verify-kestrelmq";

export const runtime = "nodejs"; // uses node:crypto

const SECRETS = (process.env.KESTRELMQ_SIGNING_SECRETS ?? "")
  .split(",")
  .map((s) => s.trim())
  .filter(Boolean);

export async function POST(request: Request) {
  const rawBody = Buffer.from(await request.arrayBuffer());

  const ok = verifyKestrelMQ(
    rawBody,
    request.headers.get("x-kestrelmq-timestamp"),
    request.headers.get("x-kestrelmq-signature"),
    SECRETS,
  );
  if (!ok) return NextResponse.json({ error: "invalid signature" }, { status: 401 });

  const deliveryId = request.headers.get("x-kestrelmq-delivery-id");
  if (!deliveryId) return NextResponse.json({ error: "missing delivery id" }, { status: 400 });
  if (await alreadyProcessed(deliveryId)) return NextResponse.json({ ok: true });

  await enqueueForProcessing(deliveryId, JSON.parse(rawBody.toString("utf8")));
  return NextResponse.json({ ok: true });
}

Python verifier

verify_kestrelmq.py
import hashlib
import hmac
import re
import time
from typing import Iterable

TOLERANCE_SEC = 300
_TIMESTAMP = re.compile(r"^\d{1,12}$")
_HEX_64 = re.compile(r"^[0-9a-fA-F]{64}$")


def verify_kestrelmq(
    raw_body: bytes,
    timestamp_header: str | None,
    signature_header: str | None,
    secrets: Iterable[str],
    tolerance_sec: int = TOLERANCE_SEC,
) -> bool:
    if not timestamp_header or not signature_header or not _TIMESTAMP.match(timestamp_header):
        return False
    if abs(int(time.time()) - int(timestamp_header)) > tolerance_sec:
        return False  # replay or clock skew

    # During a rotation grace window the header is "v1=<new>,v1=<old>".
    provided = [
        part.strip()[3:].lower()
        for part in signature_header.split(",")
        if part.strip().startswith("v1=") and _HEX_64.match(part.strip()[3:])
    ]
    if not provided:
        return False

    ok = False
    for secret in secrets:
        mac = hmac.new(secret.encode("utf-8"), digestmod=hashlib.sha256)
        mac.update(f"{timestamp_header}.".encode("utf-8"))
        mac.update(raw_body)
        expected = mac.hexdigest()
        for candidate in provided:
            if hmac.compare_digest(expected, candidate):
                ok = True  # keep looping: no early exit
    return ok

FastAPI

Read await request.body() before parsing, and do not declare a Pydantic body parameter on this route:

main.py
import json
import os

from fastapi import FastAPI, Header, HTTPException, Request

from verify_kestrelmq import verify_kestrelmq

app = FastAPI()
SECRETS = [s.strip() for s in os.environ.get("KESTRELMQ_SIGNING_SECRETS", "").split(",") if s.strip()]


@app.post("/webhooks/kestrelmq")
async def kestrelmq_webhook(
    request: Request,
    x_kestrelmq_timestamp: str | None = Header(default=None),
    x_kestrelmq_signature: str | None = Header(default=None),
    x_kestrelmq_delivery_id: str | None = Header(default=None),
):
    raw_body = await request.body()
    if not verify_kestrelmq(raw_body, x_kestrelmq_timestamp, x_kestrelmq_signature, SECRETS):
        raise HTTPException(status_code=401, detail="invalid signature")
    if not x_kestrelmq_delivery_id:
        raise HTTPException(status_code=400, detail="missing delivery id")
    if await already_processed(x_kestrelmq_delivery_id):
        return {"ok": True}

    await enqueue_for_processing(x_kestrelmq_delivery_id, json.loads(raw_body))
    return {"ok": True}

Signatures prove origin, not uniqueness

KestrelMQ is at-least-once, so a valid signature can arrive twice after a timeout, a sweeper re-enqueue or a manual replay (see how at-least-once delivery works). Deduplicate on X-KestrelMQ-Delivery-Id, which is identical on every retry and replay. X-KestrelMQ-Event-Id is shared by every delivery fanned out from one event; use it only to correlate.

idempotency.ts
import { redis } from "./redis";

const DEDUPE_TTL_SEC = 24 * 60 * 60;

/** Returns true if this delivery was already claimed. */
export async function alreadyProcessed(deliveryId: string): Promise<boolean> {
  const claimed = await redis.set(`kmq:delivery:${deliveryId}`, "1", "EX", DEDUPE_TTL_SEC, "NX");
  return claimed === null;
}

With a database, a unique constraint on delivery_id plus INSERT ... ON CONFLICT DO NOTHING survives a Redis flush. If your handler can crash after claiming, store a status (processing, done) and skip only done. Respond 2xx fast: the per-attempt timeout is 10 seconds, and a slow handler that eventually succeeds still produces a retry.

Checklist

  • Verify over raw bytes, before parsing, signing the timestamp string as received.
  • Reject timestamps outside 300 seconds.
  • Compare in constant time; check every comma-separated v1= entry.
  • Keep secrets in a manager so rotation never needs a coordinated deploy.
  • Deduplicate on X-KestrelMQ-Delivery-Id; return 2xx quickly.

Next step

Rotate a test workspace's secret now and run rotation-check.sh against your receiver. Then read how outbound requests are kept off your network in SSRF protection for webhook workers, or boot the stack with the Docker quickstart. Agents can inspect each signed attempt through the MCP inspect_delivery tool.

FAQ

How does KestrelMQ sign outbound webhooks?

Every attempt carries X-KestrelMQ-Timestamp (Unix seconds) and X-KestrelMQ-Signature in the form v1=<hex>, where the hex value is HMAC-SHA256 of the string "{timestamp}.{rawBody}" keyed with the workspace webhook signing secret (a whsec_ string). Verify it over the exact raw request bytes.

How do I rotate the signing secret without dropping webhooks?

Call POST /v1/workspaces/:id/rotate-secret. KestrelMQ keeps the previous secret for gracePeriodHours (default 24 from SECRET_ROTATION_GRACE_HOURS, maximum 720, 0 for immediate invalidation) and signs each attempt with both secrets, sending X-KestrelMQ-Signature as v1=<new_hex>,v1=<old_hex>. A receiver that accepts any matching v1= entry verifies with either secret, so you deploy the new secret at your own pace.

Why must I verify against the raw body instead of parsed JSON?

The signature covers the exact bytes KestrelMQ sent. Re-serializing parsed JSON changes whitespace, key order or number formatting and breaks a valid signature. Capture the raw bytes before any JSON middleware runs.

How do I prevent replay attacks?

The timestamp is part of the signed string. Reject any request whose timestamp differs from your clock by more than 300 seconds, and deduplicate on X-KestrelMQ-Delivery-Id so a captured request cannot trigger side effects twice.

Run guaranteed webhook delivery on your own infrastructure

KestrelMQ is MIT-licensed and boots with a single Docker Compose file. Follow the quickstart or start in the hosted dashboard.