Verify signatures
Prove each webhook came from Railbed and wasn't changed. The signing scheme, verification code in six languages, how to get the raw body in common frameworks, and a test vector.
On this page
How deliveries are signed
Every delivery carries a Railbed-Signature header:
Railbed-Signature: t=1790381342,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdtis when this attempt was signed, in Unix seconds.- Each
v1is the hex HMAC-SHA256 of the string{t}.{raw body}, keyed with an endpoint signing secret: the wholewhsec_…value, as text. For 24 hours after you roll a secret, the header has twov1values, one for the current key and one for the previous key. - A signing secret is
whsec_followed by 43 URL-safe characters (A–Z,a–z,0–9,-and_), 49 characters in all; the test vector below uses a shorter one. Store it exactly as copied: a leading or trailing space or a newline becomes part of the HMAC key, and every signature then fails to match.
To verify a delivery:
- Read the header and split out
tand everyv1. Reject a missing or malformed header; require one timestamp followed by one or morev1=<64 hex characters>values. - Reject it if
tis more than five minutes from your clock. This stops someone replaying an old delivery they captured. - Compute HMAC-SHA256 over
t, a full stop and the raw request body, with your secret as the key, and hex-encode it. - Compare your result with each
v1in constant time. Accept when any signature matches; reject when none match. Keep everyv1value when parsing—putting them in a plain key/value map loses one during rotation.
Each attempt is signed afresh, so a retry has a new t and v1 for the same body.
During the overlap, update your server to the new secret shown in Developers. Once 24 hours have passed, only the current key signs deliveries. Rolling again during the overlap ends it early, so the key from before the last roll stops signing at once (Rolling a secret). If an endpoint must stop immediately, remove it; removal stops delivery rather than continuing the overlap.
Verify a delivery
Each function returns true only for a genuine, recent delivery. Check yours against the test vector below.
import crypto from 'node:crypto';
export function verifyRailbedSignature(
rawBody,
header,
secret,
toleranceSeconds = 300,
) {
const match = /^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/.exec(header ?? '');
if (!match) return false;
const [, timestamp, signatures] = match;
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (age > toleranceSeconds) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
return signatures.slice(1).split(',').some((part) =>
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(part.slice(3))),
);
}Cloudflare Workers, Deno, Bun, Next.js route handlers
export async function verifyRailbedSignature(
rawBody: string,
header: string | null,
secret: string,
toleranceSeconds = 300,
) {
const match = /^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/.exec(header ?? '');
if (!match) return false;
const [, timestamp, signatures] = match;
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (age > toleranceSeconds) return false;
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
enc.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify'],
);
const signedPayload = enc.encode(`${timestamp}.${rawBody}`);
// subtle.verify compares in constant time
for (const part of signatures.slice(1).split(',')) {
const bytes = new Uint8Array(part.slice(3).match(/../g)!.map((h) => parseInt(h, 16)));
if (await crypto.subtle.verify('HMAC', key, bytes, signedPayload)) return true;
}
return false;
}import hashlib, hmac, re, time
def verify_railbed_signature(
raw_body: bytes,
header: str,
secret: str,
tolerance_seconds: int = 300,
) -> bool:
match = re.fullmatch(r"t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)", header or "")
if not match:
return False
timestamp, signatures = match.groups()
if abs(time.time() - int(timestamp)) > tolerance_seconds:
return False
expected = hmac.new(
secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256
).hexdigest()
return any(hmac.compare_digest(expected, part[3:]) for part in signatures[1:].split(","))<?php
function verify_railbed_signature(
string $rawBody,
string $header,
string $secret,
int $toleranceSeconds = 300
): bool {
if (!preg_match('/^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$/D', $header, $match)) return false;
[, $timestamp, $signatures] = $match;
if (abs(time() - (int) $timestamp) > $toleranceSeconds) return false;
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach (explode(',', substr($signatures, 1)) as $part) {
if (hash_equals($expected, substr($part, 3))) return true;
}
return false;
}require 'openssl'
require 'rack/utils' # secure_compare; Rails and Sinatra already load it
def verify_railbed_signature(raw_body, header, secret, tolerance_seconds = 300)
match = /\At=(\d{1,12})((?:,v1=[0-9a-f]{64})+)\z/.match(header.to_s)
return false unless match
timestamp, signatures = match.captures
return false if (Time.now.to_i - timestamp.to_i).abs > tolerance_seconds
expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{raw_body}")
signatures[1..].split(',').any? { |part| Rack::Utils.secure_compare(expected, part[3..]) }
endpackage railbed
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"regexp"
"strconv"
"strings"
"time"
)
var signatureHeader = regexp.MustCompile(`^t=(\d{1,12})((?:,v1=[0-9a-f]{64})+)$`)
func VerifySignature(
rawBody []byte,
header, secret string,
tolerance time.Duration,
) bool {
m := signatureHeader.FindStringSubmatch(header)
if m == nil {
return false
}
ts, err := strconv.ParseInt(m[1], 10, 64)
if err != nil {
return false
}
if age := time.Since(time.Unix(ts, 0)); age > tolerance || age < -tolerance {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(m[1] + "."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))
for _, part := range strings.Split(m[2][1:], ",") {
if hmac.Equal([]byte(expected), []byte(part[3:])) {
return true
}
}
return false
}Use the raw body
The signature covers the exact bytes Railbed sent. If your framework parses the JSON and you serialize it again, spacing, key order or escaping can change and the signature won't match. Read the body as text or bytes, verify it, then parse it.
| Framework | The raw body |
|---|---|
| Express | express.raw({ type: 'application/json' }) on the webhook route, then req.body.toString('utf8') |
| Fastify | Add a content-type parser with parseAs: 'string' for the route, or use fastify-raw-body |
| Next.js (App Router) | const raw = await request.text() in the route handler |
| Cloudflare Workers, Deno, Bun | const raw = await request.text() |
| Flask | request.get_data() |
| Django | request.body |
| FastAPI | raw = await request.body() |
| Laravel | $request->getContent() |
| Plain PHP, WordPress | file_get_contents('php://input') |
| Rails | request.raw_post |
Go net/http | io.ReadAll(r.Body) before anything else reads it |
export async function POST(request: Request) {
const raw = await request.text();
const header = request.headers.get('Railbed-Signature');
const secret = process.env.RAILBED_WEBHOOK_SECRET!;
if (!(await verifyRailbedSignature(raw, header, secret))) {
return new Response('Invalid signature', { status: 400 });
}
const event = JSON.parse(raw);
// Record event.id with a unique constraint, queue the work, then answer.
return new Response(null, { status: 200 });
}Test vector
Check your code against these known values. The secret is an example only; it isn't a real endpoint's.
| Input | Value |
|---|---|
| Secret | whsec_4mJ9pQx2VtR7cY1nKs8LwZ3bHd6fGa0e |
Timestamp t | 1790380800 |
| Raw body | {"id":"evt_ExampleEventId0001","type":"ping","created":1790380800,"livemode":false,"data":{"payment":null,"order":null,"customer":null,"invoice":null}} |
| String to sign | 1790380800.{"id":"evt_ExampleEventId0001",…}: the timestamp, a full stop, then the body |
Expected v1 | ffa4d1ef497dab81940a1183234f88da04bb2e7cd2dbb1637c71ba8348fd3f9e |
printf '%s' '1790380800.' \
'{"id":"evt_ExampleEventId0001","type":"ping","created":1790380800,' \
'"livemode":false,"data":{"payment":null,"order":null,"customer":null,"invoice":null}}' \
| openssl dgst -sha256 -hmac 'whsec_4mJ9pQx2VtR7cY1nKs8LwZ3bHd6fGa0e'The timestamp is in the past, so a verifier with a five-minute tolerance rejects this header. To test with it, pass a very large tolerance (every function above takes one), or test the HMAC step on its own. Change one byte of the body and the result must be false.
For an end-to-end check, choose Send test event (Test) or Send ping (Live) on your endpoint in Developers: the result shows whether your server accepted it.
Replays and clock skew
The five-minute window assumes your server's clock is right; keep it synced with NTP. A captured delivery replayed within the window still has a valid signature, which is why you also deduplicate on the event id: a replay of an event you've processed then changes nothing.
Rolling a secret
Roll secret creates a new secret and a 24-hour overlap. Each delivery, including retries, carries two v1 values during that window. The examples above accept any matching signature, so your receiver can keep using the previous key while you update it to the new one.
Reveal the new secret in Developers, store it on your server, and send a Test event or ping to verify it. Rolling or revealing a secret asks you to sign in again if you last signed in more than five minutes ago, except the first reveal of an endpoint you added yourself in the last five minutes. The dashboard shows when the previous key expires. After that time only the new key signs deliveries. If a secret leaks during the overlap, roll again: the secret from before the last roll stops signing at once, and the one you're replacing signs beside the new one for the next 24 hours. Your server stops trusting a leaked secret as soon as it verifies with the new one only. Remove the endpoint if it must stop receiving immediately. Secret reveals and rolls are recorded with the person who performed them.
Troubleshooting
| Symptom | Likely cause |
|---|---|
| Every delivery fails verification | The wrong secret (Test and Live endpoints have different ones, and each endpoint has its own), or a secret with extra spaces or quotes around it |
| Only some deliveries fail | The body was parsed and re-serialized before verifying. Verify the raw body |
| Test events pass, real ones fail | A proxy, CDN or security plugin changes the body or strips the Railbed-Signature header on real traffic. Allow the webhook path through untouched |
| Fails after a while | Your server's clock has drifted beyond five minutes |
Your server answered 2xx but verification failed | Check the order: verify first, then answer. A 2xx stops retries |