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:

The header
Railbed-Signature: t=1790381342,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
  • t is when this attempt was signed, in Unix seconds.
  • Each v1 is the hex HMAC-SHA256 of the string {t}.{raw body}, keyed with an endpoint signing secret: the whole whsec_… value, as text. For 24 hours after you roll a secret, the header has two v1 values, 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:

  1. Read the header and split out t and every v1. Reject a missing or malformed header; require one timestamp followed by one or more v1=<64 hex characters> values.
  2. Reject it if t is more than five minutes from your clock. This stops someone replaying an old delivery they captured.
  3. Compute HMAC-SHA256 over t, a full stop and the raw request body, with your secret as the key, and hex-encode it.
  4. Compare your result with each v1 in constant time. Accept when any signature matches; reject when none match. Keep every v1 value 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))),
  );
}

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.

FrameworkThe raw body
Expressexpress.raw({ type: 'application/json' }) on the webhook route, then req.body.toString('utf8')
FastifyAdd 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, Bunconst raw = await request.text()
Flaskrequest.get_data()
Djangorequest.body
FastAPIraw = await request.body()
Laravel$request->getContent()
Plain PHP, WordPressfile_get_contents('php://input')
Railsrequest.raw_post
Go net/httpio.ReadAll(r.Body) before anything else reads it
A complete Cloudflare Worker or Next.js route handler
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.

InputValue
Secretwhsec_4mJ9pQx2VtR7cY1nKs8LwZ3bHd6fGa0e
Timestamp t1790380800
Raw body{"id":"evt_ExampleEventId0001","type":"ping","created":1790380800,"livemode":false,"data":{"payment":null,"order":null,"customer":null,"invoice":null}}
String to sign1790380800.{"id":"evt_ExampleEventId0001",…}: the timestamp, a full stop, then the body
Expected v1ffa4d1ef497dab81940a1183234f88da04bb2e7cd2dbb1637c71ba8348fd3f9e
Reproduce it with OpenSSL
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

SymptomLikely cause
Every delivery fails verificationThe 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 failThe body was parsed and re-serialized before verifying. Verify the raw body
Test events pass, real ones failA 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 whileYour server's clock has drifted beyond five minutes
Your server answered 2xx but verification failedCheck the order: verify first, then answer. A 2xx stops retries

Updated · This page as Markdown