Verifying webhook deliveries
This page is for whoever builds the system that receives a webhook, and for the staff Admin who hands them the secret. Every delivery is signed, so the receiver can be sure it came from Adiutor and wasn’t changed on the way. Adding a webhook is covered in Webhooks.
The secret is shown once, in the dialog right after you add the webhook (or renew its secret):
What a delivery looks like
Section titled “What a delivery looks like”Adiutor sends a POST with a JSON body and three headers. Chat messages carry the same headers, though chat services ignore them.
| Header | Holds |
|---|---|
webhook-id |
The delivery’s ID. It is the same on every attempt, and when you press Send again. |
webhook-timestamp |
When this attempt was sent, in whole seconds since 1970 (UTC). Each attempt has a new one. |
webhook-signature |
v1, and a base64 signature. The header may hold several signatures, separated by spaces. Adiutor sends one. |
Test deliveries (the type webhook.test, from Send a test) are signed in the same way.
How the signature is made
Section titled “How the signature is made”- The secret is
whsec_followed by base64. The key is what that base64 decodes to, not the text of the secret. - The signed string is the
webhook-id, a dot, thewebhook-timestamp, a dot, and the body exactly as it was received. - The signature is the HMAC-SHA256 of that string with the key, in base64, after
v1,.
What the receiver must do
Section titled “What the receiver must do”- Verify before you parse. The signature covers the body byte for byte, so use the raw body, not JSON that was parsed and written out again.
- Compare in constant time, with the function your language offers for it.
- Refuse a timestamp more than 5 minutes off. Retries get a new timestamp, so this never blocks one.
- Remember the
webhook-idof what you handled, and skip a delivery you have seen: delivery is at least once. Retries and Send again keep the ID. Still answer 2xx to a repeat. - Answer any 2xx status within 10 seconds, and do the work afterwards. The answer’s body is ignored.
- Never answer 410 Gone unless the endpoint is gone for good: Adiutor then turns the webhook off at once. Never redirect: a redirect counts as a failure.
A delivery that fails is tried again after 5 minutes, 30 minutes, 2 hours, 8 hours and 24 hours, and a webhook whose deliveries fail for 3 days turns itself off. See Deliveries.
Examples
Section titled “Examples”Each function takes the secret, the headers and the raw body. It returns true when the timestamp is within 5 minutes and one of the signatures matches. The headers are each header’s name with its text, as req.headers in Node.js, request.headers in Flask or Django, or getallheaders() in PHP give them. The functions use only what the language ships with.
import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyWebhook(secret, headers, rawBody, toleranceSeconds = 300) { const id = headers['webhook-id']; const timestamp = headers['webhook-timestamp']; const signatures = headers['webhook-signature']; if (!id || !timestamp || !signatures || !secret.startsWith('whsec_')) { return false; }
// Refuse a message that is too old (or from the future). const age = Math.abs(Date.now() / 1000 - Number(timestamp)); if (!Number.isFinite(age) || age > toleranceSeconds) { return false; }
// The key is the base64 after "whsec_", decoded: not the text of the secret. const key = Buffer.from(secret.slice('whsec_'.length), 'base64'); const expected = createHmac('sha256', key) .update(`${id}.${timestamp}.`) .update(rawBody) // a string or a Buffer, exactly as received .digest();
// The header may hold several signatures, separated by spaces. return signatures.split(' ').some((candidate) => { const [version, value] = candidate.split(','); if (version !== 'v1' || !value) { return false; } const given = Buffer.from(value, 'base64'); return given.length === expected.length && timingSafeEqual(given, expected); });}import base64import hashlibimport hmacimport time
def verify_webhook(secret, headers, raw_body, tolerance_seconds=300): webhook_id = headers.get('webhook-id') timestamp = headers.get('webhook-timestamp') signatures = headers.get('webhook-signature') if not webhook_id or not timestamp or not signatures or not secret.startswith('whsec_'): return False
# Refuse a message that is too old (or from the future). try: age = abs(time.time() - int(timestamp)) except ValueError: return False if age > tolerance_seconds: return False
# The key is the base64 after "whsec_", decoded: not the text of the secret. key = base64.b64decode(secret[len('whsec_'):]) if isinstance(raw_body, str): raw_body = raw_body.encode() # but prefer the bytes exactly as received signed = f'{webhook_id}.{timestamp}.'.encode() + raw_body expected = hmac.new(key, signed, hashlib.sha256).digest()
# The header may hold several signatures, separated by spaces. for candidate in signatures.split(' '): version, _, value = candidate.partition(',') if version != 'v1': continue try: given = base64.b64decode(value, validate=True) except ValueError: continue if hmac.compare_digest(given, expected): return True return False<?php
function verifyWebhook(string $secret, array $headers, string $rawBody, int $toleranceSeconds = 300): bool{ $headers = array_change_key_case($headers, CASE_LOWER); $id = $headers['webhook-id'] ?? ''; $timestamp = $headers['webhook-timestamp'] ?? ''; $signatures = $headers['webhook-signature'] ?? ''; if ($id === '' || $signatures === '' || !ctype_digit($timestamp) || !str_starts_with($secret, 'whsec_')) { return false; }
// Refuse a message that is too old (or from the future). if (abs(time() - (int) $timestamp) > $toleranceSeconds) { return false; }
// The key is the base64 after "whsec_", decoded: not the text of the secret. $key = base64_decode(substr($secret, strlen('whsec_')), true); if ($key === false) { return false; } $expected = hash_hmac('sha256', "$id.$timestamp.$rawBody", $key, true);
// The header may hold several signatures, separated by spaces. foreach (explode(' ', $signatures) as $candidate) { [$version, $value] = array_pad(explode(',', $candidate, 2), 2, ''); $given = base64_decode($value, true); if ($version === 'v1' && $given !== false && hash_equals($expected, $given)) { return true; } } return false;}Getting the raw body
Section titled “Getting the raw body”Your framework may parse the body before your code sees it. Ask for it untouched:
- Express:
express.rawon the route, with itstypeoption set toapplication/json;req.bodyis then a Buffer. - Flask:
request.get_data(). - Django:
request.body. - Laravel:
$request->getContent(). - Plain PHP:
file_get_contents('php://input').
Libraries
Section titled “Libraries”Adiutor signs as the Standard Webhooks specification describes, so the specification’s libraries, for many languages, can check these deliveries too.
Renewing the secret
Section titled “Renewing the secret”When you press Renew secret, the old secret stops working at once. Deliveries signed with the new one fail on a receiver that still has the old one, and they are tried again, so update the receiver soon.
Example
Section titled “Example”Gita GitHub renews the secret of “Procurement” after a developer leaves. The dialog shows “Signing secret renewed. Copy the signing secret”. Gita sends it to the new developer, who replaces it in the receiver’s settings. Deliveries refused in between show as tried again on the Deliveries card, and arrive once the receiver has the new secret.
Who can do this
Section titled “Who can do this”Only staff Admins see the secret, and only once. Everyone else gets the “This page doesn’t exist or you don’t have access to it.” page. Whoever builds the receiver needs no account: the secret is all they need.
Good to know
Section titled “Good to know”- A secret can’t be shown again. Lost it? Renew it.
- Send a test on the webhook’s page shows whether your receiver answered 2xx.
- The delivery holds people by name and side only, never email addresses.
Related
Section titled “Related”Adiutor's code is released under the MIT License. The Adiutor name and logo aren’t covered by it; see the notice.
Set in Inter and JetBrains Mono, under the SIL Open Font License (Inter, JetBrains Mono).