Verifying webhooks
Check every webhook's signature before you act on it, so nobody can fake or replay an event.
Each request has an x-tracking-signature header with a Unix timestamp and an HMAC-SHA256 digest:
x-tracking-signature: t=1792560000,v1=<hex digest>
digest = HMAC_SHA256(webhook_secret, "<t>.<raw request body>")Your webhook secret (whsec_…) is shown once, when you create the endpoint. While you're rotating the secret, the header carries one v1 per secret:
x-tracking-signature: t=1792560000,v1=<hex, new secret>,v1=<hex, old secret>To verify a request:
Read the raw body, before any JSON parsing.
Split the header on
,and readtand everyv1.Reject the request if
tis more than 5 minutes from now. This stops replays.Compute the HMAC-SHA256 of
<t>.<raw body>with your secret, as hex.Compare it with each
v1in constant time. The request is valid if any one matches.
Use the raw body
Compute the digest over the body exactly as it arrived. Parsing and re-serialising the JSON changes the bytes, and the signature stops matching.
With a library
Each library verifies the signature, checks the timestamp (5 minutes by default) and parses the event in one call. It fails if anything is wrong.
- TypeScript
- Python
- Go
- Ruby
- PHP
import { Trackified } from "trackified";
// rawBody: string, Buffer or Uint8Array, exactly as received
const event = await Trackified.webhooks.constructEvent(
rawBody,
request.headers["x-tracking-signature"],
process.env.TRACKIFIED_WEBHOOK_SECRET!,
); // throws SignatureVerificationErrorimport trackified
# raw_body: bytes, exactly as received
event = trackified.construct_event(
raw_body,
headers["x-tracking-signature"],
os.environ["TRACKIFIED_WEBHOOK_SECRET"],
) # raises trackified.WebhookVerificationErrorbody, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "read error", http.StatusBadRequest)
return
}
event, err := trackified.ConstructEvent(body, r.Header.Get(trackified.SignatureHeader), os.Getenv("TRACKIFIED_WEBHOOK_SECRET"))
if err != nil { // trackified.ErrInvalidSignature
http.Error(w, "bad signature", http.StatusBadRequest)
return
}event = Trackified::WebhookSignature.construct_event(
request.raw_post,
request.headers["x-tracking-signature"],
ENV.fetch("TRACKIFIED_WEBHOOK_SECRET")
) # raises Trackified::SignatureVerificationErroruse Trackified\WebhookSignature;
$event = WebhookSignature::constructEvent(
$request->getContent(),
$request->header('x-tracking-signature', ''),
env('TRACKIFIED_WEBHOOK_SECRET'),
); // throws Trackified\Exception\SignatureVerificationErrorTo get a yes or no instead of an exception, use verify with the same arguments: Trackified.webhooks.verify, trackified.verify, trackified.VerifyWebhook, Trackified::WebhookSignature.verify or WebhookSignature::verify. Each also takes a tolerance if you need more or less than 5 minutes.
Why a request was rejected
From version 0.2, a failed verification says why. The exception carries a reason, and verifyDetailed (verify_detailed, VerifyDetailed) returns {valid, reason} without throwing.
Reason | Meaning |
|---|---|
| No signature header, or no secret configured. |
| The header has no |
|
|
| No signature matches. Usually the wrong secret, or a body that was parsed and re-serialised. |
Log the reason, but answer every rejected request with the same 400.
Rotate the secret
Rotate the secret if it leaks, or on a schedule. The old secret keeps working for a window you choose, so no event is lost while you deploy.
- Ask for a new secret
Call
POST /v1/webhooks/{id}/rotate-secretwithexpires_in_hours(default 24, at most 168), orrotateSecretin a library. The response has the newsecret, once, andprevious_secret_expires_at.curl -X POST https://api.trackified.net/v1/webhooks/wh_.../rotate-secret \ -H "Authorization: Bearer $TRACKIFIED_API_KEY" \ -H "Content-Type: application/json" \ -d '{"expires_in_hours": 24}' - Verify with both secrets
Until
previous_secret_expires_at, every delivery is signed with both secrets. Deploy your handler with both, new first. Every library's verify functions take a list of secrets and accept the request if any matches.- TypeScript
- Python
- Go
- Ruby
- PHP
const event = await Trackified.webhooks.constructEvent(rawBody, header, [newSecret, oldSecret]);event = trackified.construct_event(raw_body, header, [new_secret, old_secret])event, err := trackified.ConstructEventSecrets(body, header, []string{newSecret, oldSecret})event = Trackified::WebhookSignature.construct_event(raw_body, header, [new_secret, old_secret])$event = WebhookSignature::constructEvent($payload, $header, [$newSecret, $oldSecret]); - Drop the old secret
Once the window ends, remove the old secret from your config. To end the window early, rotate with
expires_in_hours: 0: that drops the old secret at once.
Don't rotate again before you've deployed the new secret. A second rotation drops the original secret at once: the secret from the first rotation becomes the old one, with a fresh window. Because a rotation isn't safe to repeat, the TypeScript library doesn't retry rotateSecret.
Every library page has a full handler for that language's usual web framework.
Without a library
- Node.js
- Python
import { createHmac, timingSafeEqual } from "node:crypto";
// header: the x-tracking-signature value, e.g. "t=1792560000,v1=5f2c…"
// rawBody: the request body exactly as received, before JSON.parse
// secrets: your secret, or [newSecret, oldSecret] while rotating
export function verifyTrackifiedSignature(header, rawBody, secrets) {
let timestamp;
const signatures = [];
for (const part of (header ?? "").split(",")) {
const [key, value] = part.trim().split("=", 2);
if (key === "t") timestamp = value;
else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value ?? "")) signatures.push(Buffer.from(value, "hex"));
}
if (!/^\d+$/.test(timestamp ?? "") || signatures.length === 0) return false;
// Reject events older than five minutes to stop replays.
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 5 * 60) return false;
for (const secret of [secrets].flat()) {
const expected = createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest();
if (signatures.some((sig) => timingSafeEqual(sig, expected))) return true;
}
return false;
}import hashlib
import hmac
import time
def verify_trackified_signature(header: str, raw_body: bytes, secrets: list[str]) -> bool:
"""header: the x-tracking-signature value. raw_body: the body exactly as received.
secrets: [your_secret], or [new_secret, old_secret] while rotating."""
timestamp, signatures = "", []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t":
timestamp = value
elif key == "v1":
signatures.append(value)
if not timestamp.isdigit() or not signatures:
return False
# Reject events older than five minutes to stop replays.
if abs(time.time() - int(timestamp)) > 300:
return False
signed = timestamp.encode() + b"." + raw_body
for secret in secrets:
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
if any(hmac.compare_digest(expected, sig) for sig in signatures):
return True
return FalseTest your code
POST /v1/webhooks/{id}/test returns a signed sample event without sending it: a signature header value and the body it signs, as a sample tracking.updated event. During a rotation the signature carries both v1 values, like a real delivery. The body comes back parsed, so serialise it compactly (JSON.stringify(body) in JavaScript, json.dumps(body, separators=(",", ":")) in Python) to get the signed bytes. Then feed both to your verification code within 5 minutes.
The CLI can check a signature too. It exits with status 1 if the signature is invalid:
trackified verify-webhook --secret "$TRACKIFIED_WEBHOOK_SECRET" \
--header "t=1792560000,v1=5f2c..." --body-file body.json