Verify webhook signatures
Before you begin
- Plan
- Included in Pro and Team. How plans and limits work
- Role
- Admin or higher to read the signing secret.
- You need
- A webhook and a receiver you can change
Anyone who learns your receiver’s address can post to it. Every MockHub delivery is signed with the webhook’s own secret, so your receiver can accept what MockHub sent and refuse everything else. The scheme itself is described in Webhook signatures and retries.
-
Open the project’s Webhooks tab.
-
Select More actions on the webhook.
-
Select Show secret.
-
Select Copy.
-
Select Done.
-
Give the secret to your receiver through its configuration, such as an environment variable named
MOCKHUB_WEBHOOK_SECRET, never in its source code. -
Add the check below to the receiver, and answer
401to a request that fails it. -
Select Deliveries on the webhook.
-
Select Send a test.
Check each delivery
Section titled “Check each delivery”Each sample receives deliveries at /hooks/orders, checks the signature against the body exactly as it arrived, and allows five minutes between the delivery’s timestamp and the receiver’s clock.
With Express, express.raw() keeps the body as the bytes that were signed. A JSON parser in front of the route would lose them.
import { createHmac, timingSafeEqual } from 'node:crypto';import express from 'express';
const TOLERANCE_SECONDS = 300;
function verifyMockHubSignature( secret, rawBody, timestamp, signature, now = Math.floor(Date.now() / 1000),) { if (!secret || !/^\d+$/.test(timestamp ?? '')) { return false; } if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) { return false; } if (!signature?.startsWith('v1=')) { return false; } const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest(); const received = Buffer.from(signature.slice(3), 'hex'); return received.length === expected.length && timingSafeEqual(received, expected);}
const app = express();
// express.raw() keeps req.body as the exact bytes MockHub signed.app.post('/hooks/orders', express.raw({ type: '*/*' }), (req, res) => { const valid = Buffer.isBuffer(req.body) && verifyMockHubSignature( process.env.MOCKHUB_WEBHOOK_SECRET, req.body, req.get('X-MockHub-Timestamp'), req.get('X-MockHub-Signature'), ); if (!valid) { return res.sendStatus(401); } const event = JSON.parse(req.body.toString('utf8')); // Handle the event, then answer quickly with a 2xx. res.sendStatus(204);});
app.listen(3000);With Flask, request.get_data() returns the body as the bytes that were signed.
import hashlibimport hmacimport jsonimport osimport time
from flask import Flask, abort, request
TOLERANCE_SECONDS = 300
def verify_mockhub_signature( secret: str, raw_body: bytes, timestamp: str, signature: str, now: int | None = None) -> bool: if not secret or not (timestamp.isascii() and timestamp.isdigit()): return False now = int(time.time()) if now is None else now if abs(now - int(timestamp)) > TOLERANCE_SECONDS: return False if not signature.startswith("v1="): return False signed = timestamp.encode() + b"." + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return hmac.compare_digest(expected.encode(), signature[3:].encode())
app = Flask(__name__)
@app.post("/hooks/orders")def orders_hook(): raw_body = request.get_data() # the exact bytes MockHub signed if not verify_mockhub_signature( os.environ.get("MOCKHUB_WEBHOOK_SECRET", ""), raw_body, request.headers.get("X-MockHub-Timestamp", ""), request.headers.get("X-MockHub-Signature", ""), ): abort(401) event = json.loads(raw_body) # Handle the event, then answer quickly with a 2xx. return "", 204php://input holds the body as the bytes that were signed.
<?php
const MOCKHUB_TOLERANCE_SECONDS = 300;
function verifyMockHubSignature( string $secret, string $rawBody, string $timestamp, string $signature, ?int $now = null,): bool { if ($secret === '' || !ctype_digit($timestamp)) { return false; } if (abs(($now ?? time()) - (int) $timestamp) > MOCKHUB_TOLERANCE_SECONDS) { return false; } if (!str_starts_with($signature, 'v1=')) { return false; } $expected = hash_hmac('sha256', $timestamp.'.'.$rawBody, $secret);
return hash_equals($expected, substr($signature, 3));}
$rawBody = (string) file_get_contents('php://input'); // the exact bytes MockHub signed
if (!verifyMockHubSignature( (string) getenv('MOCKHUB_WEBHOOK_SECRET'), $rawBody, $_SERVER['HTTP_X_MOCKHUB_TIMESTAMP'] ?? '', $_SERVER['HTTP_X_MOCKHUB_SIGNATURE'] ?? '',)) { http_response_code(401); exit;}
$event = json_decode($rawBody, true);// Handle the event, then answer quickly with a 2xx.http_response_code(204);io.ReadAll(r.Body) returns the body as the bytes that were signed. The route pattern needs Go 1.22 or later.
package main
import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "io" "log" "net/http" "os" "strconv" "strings" "time")
const toleranceSeconds = 300
func VerifyMockHubSignature(secret string, rawBody []byte, timestamp, signature string, now time.Time) bool { ts, err := strconv.ParseInt(timestamp, 10, 64) if err != nil || secret == "" { return false } if age := now.Unix() - ts; age > toleranceSeconds || age < -toleranceSeconds { return false } hexDigest, found := strings.CutPrefix(signature, "v1=") if !found { return false } received, err := hex.DecodeString(hexDigest) if err != nil { return false } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(timestamp + ".")) mac.Write(rawBody) return hmac.Equal(received, mac.Sum(nil))}
func ordersHook(w http.ResponseWriter, r *http.Request) { rawBody, err := io.ReadAll(r.Body) // the exact bytes MockHub signed if err != nil || !VerifyMockHubSignature(os.Getenv("MOCKHUB_WEBHOOK_SECRET"), rawBody, r.Header.Get("X-MockHub-Timestamp"), r.Header.Get("X-MockHub-Signature"), time.Now()) { http.Error(w, "invalid signature", http.StatusUnauthorized) return } // Decode rawBody with encoding/json, handle the event, then answer quickly with a 2xx. w.WriteHeader(http.StatusNoContent)}
func main() { http.HandleFunc("POST /hooks/orders", ordersHook) log.Fatal(http.ListenAndServe(":3000", nil))}What the check does, in every language:
- It signs the timestamp, a full stop and the raw body with the secret, using HMAC-SHA256, and compares the result with the hexadecimal digits after
v1=inX-MockHub-Signature. - The comparison takes the same time whether the first or the last character differs, so an attacker cannot guess the signature one character at a time.
- It refuses a timestamp more than five minutes from the receiver’s clock, so a delivery recorded by someone else cannot be sent again later. Each retry is signed afresh, so retries pass. Keep the receiver’s clock in sync.
- It refuses everything while the secret is empty, so a missing environment variable cannot let a forged delivery through.
Test your code
Section titled “Test your code”Check your code against this fixed example. Its timestamp is from 2023, so pass 1700000000 as the current time:
| Input | Value |
|---|---|
| Secret | whsec_0123456789abcdef |
X-MockHub-Timestamp |
1700000000 |
| Body | {"a":1} |
X-MockHub-Signature |
v1=9f5e37cdc7ea587c7c02062d93283cad000d66a831b2a1676418696db47ed6c2 |
console.log( verifyMockHubSignature( 'whsec_0123456789abcdef', '{"a":1}', '1700000000', 'v1=9f5e37cdc7ea587c7c02062d93283cad000d66a831b2a1676418696db47ed6c2', 1700000000, ),); // trueprint( verify_mockhub_signature( "whsec_0123456789abcdef", b'{"a":1}', "1700000000", "v1=9f5e37cdc7ea587c7c02062d93283cad000d66a831b2a1676418696db47ed6c2", now=1700000000, )) # Truevar_dump(verifyMockHubSignature( 'whsec_0123456789abcdef', '{"a":1}', '1700000000', 'v1=9f5e37cdc7ea587c7c02062d93283cad000d66a831b2a1676418696db47ed6c2', 1700000000,)); // bool(true)Save it as main_test.go in the receiver’s directory and run go test.
package main
import ( "testing" "time")
func TestVerifyMockHubSignature(t *testing.T) { valid := VerifyMockHubSignature( "whsec_0123456789abcdef", []byte(`{"a":1}`), "1700000000", "v1=9f5e37cdc7ea587c7c02062d93283cad000d66a831b2a1676418696db47ed6c2", time.Unix(1700000000, 0), ) if !valid { t.Fatal("the fixed example must verify") }}Change one character of the body or the signature, or move the current time more than 300 seconds away, and the result must be false.
Rotate the secret
Section titled “Rotate the secret”Rotate secret under the webhook’s More actions gives it a new secret once you confirm. From that moment every delivery, including retries of earlier ones, is signed with the new secret only, and your receiver refuses them until it has it.
-
Select More actions on the webhook.
-
Select Rotate secret, then Rotate secret again to confirm.
-
Select Copy, and give the new secret to your receiver.
-
Select Deliveries on the webhook.
-
Open Any status and choose Failed.
-
Select Replay on each delivery your receiver refused while it still had the old secret, and confirm with Replay. A replay is signed with the new secret.
A 401 from your receiver is not retried, so replaying is the only way those deliveries arrive.
Result
Section titled “Result”Your receiver accepts deliveries from the webhook, and answers 401 to a request with a missing, changed or stale signature.
The test delivery turns Succeeded with your receiver’s status, such as 204.
A delivery your receiver refused reads Failed with 401 in Answer.
Limits
Section titled “Limits”- The signature covers the timestamp and the body, nothing else: not the method, the address or any header, including your static headers.
- Deliveries can occasionally arrive twice. The timestamp does not prevent that, so if handling an event twice matters, remember the
X-MockHub-Deliveryof each delivery you handled and ignore a repeat. A replay is a new delivery with its ownX-MockHub-Delivery. - Each webhook has one secret at a time. MockHub does not sign with the old and the new secret during a rotation.
- MockHub keeps the secret so that it can sign, and any Admin of the workspace can read it again. Treat it as a password.
- An alert rule that calls a webhook address signs with a secret of its own, not a webhook’s: select More actions on the rule in the project’s Alerts tab, then Show secret. Its alerts carry
X-MockHub-Alert-Rule-Idwhere a webhook’s carryX-MockHub-Webhook-Id, and are checked the same way.