Skip to main content
Version: 1.4

Signing Outbound Webhooks

A webhook receiver has one question it cannot answer from the network alone: did this request really come from DeviceChain, and is it the one that was sent? Signing answers it. A signed delivery carries three headers, defined by the open Standard Webhooks specification, so a receiver can verify it with a few lines of code or with any library that implements the specification.

Signing is off by default. A webhook you have not asked to sign is delivered exactly as before, byte for byte. You can sign two kinds of delivery:

The request body is the same either way. Signing adds headers and changes nothing else.

What a signed delivery carries​

HeaderValue
webhook-idThe message's identity. It stays the same across the retries of one message, so a receiver can use it to discard a duplicate.
webhook-timestampInteger Unix seconds, taken again on every attempt. A receiver rejects one that is too old, which limits how long a captured request stays useful.
webhook-signatureOne or more space-separated entries of the form v1,<base64 HMAC-SHA256>.

The signature covers <webhook-id>.<webhook-timestamp>.<raw body>, keyed by your signing secret. Change one byte of the body, the id or the timestamp and it no longer matches.

For an httpCall action the webhook-id is the dispatch's idempotency key, the same value sent in X-DC-Idempotency-Key. For a notification channel it is a fresh msg_… id for each delivery, reused when that delivery is retried. A broker redelivering the whole alarm after a restart produces a new id, so for end-to-end de-duplication use the alarm fields in the payload as well.

The signing secret​

A signing secret looks like whsec_ followed by base64 text. It is generated by the platform, shown once in the response to the mutation that creates it, and stored sealed in the platform's encrypted secret store. After that it cannot be read back through any API: lists and lookups report only whether one exists. Copy it into your receiver's configuration when you create it.

You can have one secret per notification channel and one per signing handle. A handle is a name you choose for an httpCall secret (letters, digits and - _ . /, at most 256 characters); several rules can share one.

Sign a notification webhook channel​

Create the channel as usual, then mint its secret, then turn signing on in the channel's config. Requires notification:write.

mutation {
generateNotificationChannelSigningSecret(token: "oncall-hook") {
secret # whsec_… — shown once
}
}
mutation {
updateNotificationChannel(token: "oncall-hook", request: {
config: "{\"url\":\"https://hooks.example.com/alarms\",\"auth\":\"bearer\",\"signing\":true}"
}) { token hasSigningSecret }
}

Signing composes with the channel's auth mode: a bearer channel still sends its Authorization header, and the signature headers are added to it.

Mint the secret before you set "signing": true. A channel that is set to sign but has no secret is not sent unsigned: the delivery is refused on its first attempt and not retried, and the notification service logs the tenant and the channel's token. It is counted on devicechain_notificationmanagement_deliveries_refused_total{reason="signing"}, which you can alert on.

Sign an httpCall action​

Mint a secret under a handle, then name the handle in the action's signingSecretRef. Requires connector:write.

mutation {
generateWebhookSigningSecret(handle: "hooks/prod") {
handle
secret # whsec_… — shown once
}
}

In the rule form, the httpCall action has a Signing secret handle field, and the automation canvas has the same field on the action node. Over the API it is the signingSecretRef field of the action:

{
"type": "httpCall",
"httpCall": {
"url": "https://hooks.example.com/devices",
"bodyTemplate": "'{\"series\":\"' + series + '\"}'",
"signingSecretRef": "hooks/prod"
}
}

A rule that names a handle with no stored secret has its deliveries dead-lettered as invalid on the first attempt; the call is never made unsigned. The same happens if you delete a secret that a rule still names. The connectors service reads secrets through a cache of about a minute, so a created, rotated or deleted secret takes up to that long to reach every delivery.

To see whether a handle has a secret, and whether a rotation is open, without reading it:

query { webhookSigningSecret(handle: "hooks/prod") { handle rotating } }

Rotating a secret​

Rotation never drops a delivery, because for a while both secrets sign.

  1. Rotate. This mints a new secret, returns it once, and keeps the old one.

    mutation { rotateNotificationChannelSigningSecret(token: "oncall-hook") { secret rotating } }

    For an httpCall handle:

    mutation { rotateWebhookSigningSecret(handle: "hooks/prod") { secret rotating } }

    From now on every delivery carries two entries in webhook-signature, one under the new secret and one under the old. A receiver holding either secret accepts it.

  2. Move the receiver to the new secret at your own pace. A verifier that can hold two secrets at once makes this a non-event.

  3. End the rotation. The old secret stops signing and deliveries carry one entry again.

    mutation { endNotificationChannelSigningRotation(token: "oncall-hook") { token signingRotationOpen } }

    For an httpCall handle:

    mutation { endWebhookSigningRotation(handle: "hooks/prod") { handle rotating } }

Rotating again while a rotation is open replaces the old secret with the current one, so a secret two rotations old stops being used. To stop signing for good, remove "signing": true from the channel (or the signingSecretRef from the rule) first, and then delete the secret with deleteNotificationChannelSigningSecret or deleteWebhookSigningSecret. Deleting a channel deletes its secrets too.

Verifying a delivery​

A receiver must do four things, in this order:

  1. Take the raw body exactly as received. Parsing the JSON and serializing it again changes the bytes and breaks the signature.
  2. Check that webhook-id, webhook-timestamp and webhook-signature are all present, and that the timestamp is within a few minutes of your clock, in either direction. Five minutes is the usual tolerance.
  3. Compute HMAC-SHA256 over <id>.<timestamp>.<raw body> with the secret's key (the base64 text after whsec_, decoded), encode it as base64 and prefix v1,.
  4. Compare that with each space-separated entry of webhook-signature in constant time, and accept if any matches. Ignore entries that do not start with v1,.

The three examples below do exactly this. Pass every secret you currently hold, which is two during a rotation.

Go​

package main

import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"net/http"
"strconv"
"strings"
"time"
)

// Verify checks a delivery. body must be the raw bytes received, before any JSON decoding.
func Verify(h http.Header, body []byte, now time.Time, secrets ...string) error {
id := h.Get("webhook-id")
ts := h.Get("webhook-timestamp")
sigs := h.Get("webhook-signature")
if id == "" || ts == "" || sigs == "" {
return errors.New("missing webhook headers")
}
sec, err := strconv.ParseInt(ts, 10, 64)
if err != nil {
return errors.New("malformed webhook-timestamp")
}
// Whole seconds, not a time.Duration: a timestamp centuries away would saturate a Duration.
if sec > now.Unix()+300 || sec < now.Unix()-300 {
return errors.New("timestamp outside the tolerance window")
}
for _, secret := range secrets {
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
if err != nil {
return err
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + ts + "."))
mac.Write(body)
want := "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil))
for _, s := range strings.Fields(sigs) {
if hmac.Equal([]byte(s), []byte(want)) {
return nil
}
}
}
return errors.New("no valid signature")
}

Call it with the body read straight from the request, for example body, _ := io.ReadAll(r.Body) followed by Verify(r.Header, body, time.Now(), secret).

Node​

const crypto = require('node:crypto');

// rawBody must be the Buffer or string exactly as received, before JSON.parse.
function verify(headers, rawBody, secrets, now = Date.now()) {
const id = headers['webhook-id'];
const ts = headers['webhook-timestamp'];
const sigs = headers['webhook-signature'];
if (!id || !ts || !sigs) throw new Error('missing webhook headers');
if (!/^\d+$/.test(ts)) throw new Error('malformed webhook-timestamp');
if (Math.abs(now / 1000 - Number(ts)) > 300) throw new Error('timestamp outside the tolerance window');

for (const secret of secrets) {
const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
const want = 'v1,' + crypto.createHmac('sha256', key).update(`${id}.${ts}.`).update(rawBody).digest('base64');
for (const sig of sigs.split(' ')) {
if (sig.length === want.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return;
}
}
throw new Error('no valid signature');
}

In Express, capture the raw body with express.raw({ type: 'application/json' }) on this route, call verify(req.headers, req.body, secrets), and only then JSON.parse it. Node lower-cases header names, which is what the code expects.

Python​

import base64
import hashlib
import hmac
import time


def verify(headers, raw_body, secrets, tolerance=300, now=None):
"""Raise ValueError unless the delivery is authentic and fresh.

raw_body is the bytes exactly as received, before any JSON decoding.
"""
msg_id = headers.get("webhook-id")
ts = headers.get("webhook-timestamp")
sigs = headers.get("webhook-signature")
if not (msg_id and ts and sigs):
raise ValueError("missing webhook headers")
try:
sent = int(ts)
except ValueError:
raise ValueError("malformed webhook-timestamp")
if abs((time.time() if now is None else now) - sent) > tolerance:
raise ValueError("timestamp outside the tolerance window")

for secret in secrets:
key = base64.b64decode(secret.removeprefix("whsec_"))
digest = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()
want = "v1," + base64.b64encode(digest).decode()
for sig in sigs.split():
if hmac.compare_digest(sig, want):
return
raise ValueError("no valid signature")

In Flask use request.get_data() for raw_body and request.headers for headers; in FastAPI use await request.body(). removeprefix needs Python 3.9 or later.

Check your verifier​

The specification publishes a test vector. A correct verifier accepts it at the moment it was signed:

FieldValue
secretwhsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw
webhook-idmsg_p5jXN8AQM9LWM0D4loKWxJek
webhook-timestamp1614265330
body{"test": 2432232314}
webhook-signaturev1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=

It must reject the same request with one byte of the body changed, and with the clock an hour later.

Turning signing on during an upgrade​

Roll the upgrade out to every outbound-connectors and notification-management replica before you turn signing on. A replica from before signing existed ignores signingSecretRef and "signing": true, so while old and new replicas overlap, a delivery that lands on an old one goes out unsigned, and an old outbound-connectors replica does not know that signing secrets must never be used as a Bearer credential. Until the rollout has finished, do not set "signing": true on a channel, do not add signingSecretRef to a rule, and do not publish a rule whose Bearer secretRef begins with webhook-signing/. Enable signing afterwards.

Failure behaviour​

SituationWhat happens
Signing is not enabledThe delivery is unchanged, with no webhook-* headers.
Signing is enabled and the secret existsThe delivery carries the three headers.
Signing is enabled but no secret is stored, or the stored value is not a valid secretThe delivery is refused and not retried. Nothing is sent. A channel counts it as reason="signing"; an httpCall is dead-lettered as invalid.
The secret store is briefly unavailableThe delivery is retried, as for any transient failure.
A header you configured is named webhook-id, webhook-timestamp or webhook-signatureOn a signed delivery the platform's value replaces it.
A signed channel's authHeader is webhook-id, webhook-timestamp or webhook-signatureThe channel is refused when you save it, and a delivery is refused and not retried, because the signature would overwrite your credential. Use another header name for the credential.