QUALIA BITS ## Journal

[journal]

AI Call Webhooks: Verify the Signature Before You Trust the Callback

AI Call Webhooks: Verify the Signature Before You Trust the Callback
webhook securitysignature validationvoice AITwiliocall callbacksHMAC

A callback arrives at your endpoint claiming a call ended. Before any dashboard update or follow-up task, one question comes first: did this request actually come from your telephony provider? If an attacker can guess your webhook URL, forging that callback is a single HTTP POST. Signature validation is the check that stands in front of everything else.

TLS first, then the signature

This guide uses Twilio Programmable Voice callbacks as the concrete example, as an implementation pattern rather than a claim about features already deployed in a QualiaBits product. Twilio requires webhook URLs to use HTTPS with a valid, trusted certificate; it does not send webhooks to plain HTTP endpoints, or to endpoints with expired or self-signed certificates, unless explicitly configured for development. [SRC003]

Every webhook request carries an X-Twilio-Signature header. Twilio computes an HMAC-SHA1 over the request URL and request body fields, keyed with your Auth Token, and base64-encodes the result. Your endpoint recomputes the same value and rejects any request whose signature is missing or mismatched. Twilio's own guidance is blunt about the consequence of skipping this: without validation, your app is vulnerable to forged webhooks from anyone who can predict the URL. [SRC001] [SRC003]

Keep the order of checks fixed: signature first, payload validation second, state change last. Payload validation means required fields have values, values match expected types and ranges, the AccountSid is yours, and resource SIDs belong to your account. A valid signature from the wrong account context is still not your event. [SRC003]

The exact string that gets signed

For the common form-encoded POST, the signed string is assembled precisely: take the full request URL from the protocol through the end of the query string, sort every POST field alphabetically by name using Unix-style case-sensitive ordering, then append each field's name and value to the URL with no delimiters. Sign that string with HMAC-SHA1 using your primary Auth Token, and base64-encode the hash. [SRC001]

Query parameters are part of the URL, so they ride along inside it. Never extract query parameters and pass them separately to the validator's params argument, and never decode or re-encode the URL first: either change makes validation fail against a genuine request. [SRC002]

Twilio publishes a worked example you can test against: a fixed URL, five sorted fields and a fixed token must produce one documented signature. Our sample below reproduces that exact value as an anchor test, so the implementation is pinned to the documented algorithm rather than to our own reading of it. [SRC001]

JSON callbacks take a different path

When Twilio sends application/json, it appends a bodySHA256 query parameter to your webhook URL, carrying the hexadecimal SHA-256 of the raw request body. The SDK's JSON-specific validation method checks that the hash of the raw body matches bodySHA256, then validates the signature over the URL including that parameter. [SRC001] [SRC002]

Two consequences follow. Do not parse the JSON and feed its properties in as form fields; pass the raw body string to the JSON validation method. And treat the body as bytes: re-serializing the same JSON with keys in a different order produces different bytes, a different hash, and a failed check. Our tests cover both paths. [SRC002]

When genuine callbacks fail validation

The signature covers the exact URL Twilio called, which is the URL you configured, not necessarily the URL your application reconstructs. Behind a proxy, load balancer or framework rewrite, the two can differ: a trailing slash added by an index-page rewrite, a port kept or dropped, or an http/https scheme difference after TLS termination. Any of these flips a genuine callback to invalid. Configure validation against the real external URL. [SRC001]

Middleware that edits field values breaks the match just as surely. Twilio names Laravel's TrimStrings middleware, on by default, and notes that certain Node.js middleware may also trim whitespace from request fields. Turn those behaviors off for webhook routes. [SRC001]

Token rotation is a third trap: if you have created a secondary Auth Token, Twilio keeps signing with your previous token until the secondary one is promoted to primary. Validating against the new token rejects every genuine callback. Twilio also has no fixed range of IP addresses that issue webhooks, so IP allowlisting cannot substitute for signature checks. And Twilio explicitly recommends its SDK validation helpers over hand-rolled implementations. [SRC001] [SRC002]

A valid signature proves authenticity, not freshness

Reading the documented scheme carefully: the signed string is the URL plus sorted fields, keyed by the Auth Token. It contains no timestamp or nonce of its own. A request that was valid when captured remains valid when replayed. This is our analysis of the published algorithm, not a Twilio statement: treat the signature as proof of who sent the bytes and that they arrived intact, and build freshness and exactly-once handling separately, using stable event identity and durable deduplication records as described in our companion work on duplicate callbacks.

For comparison, our sample uses a constant-time equality check on the decoded hashes rather than a short-circuit string compare. That is our implementation choice, following general cryptographic-comparison practice; Twilio's documentation does not mandate a comparison method, and its SDK helpers handle the comparison for you. [SRC001]

On the algorithm itself: Twilio addresses SHA-1 collision concerns directly, noting that HMAC does not rely on SHA-1's collision resistance because the security comes from the secret key. The practical risks live elsewhere: leaked tokens, skipped validation, and URL reconstruction bugs. [SRC001]

A small validator you can test

This JavaScript sample illustrates the documented algorithm in about thirty lines, tested on Node 22. It exists to make the canonicalization rules concrete and to anchor the tests to Twilio's published example. For production, use the Twilio SDK's validation helpers, which handle URL and body reconstruction, HMAC computation and comparison; Twilio recommends them explicitly. [SRC001] [SRC003]

import { createHmac, createHash, timingSafeEqual } from 'node:crypto';

// Form-encoded callback: signature input is the full request URL
// followed by every POST field appended as name+value, sorted by
// name in Unix-style case-sensitive order, with no delimiters.
// HMAC-SHA1 keyed with the primary auth token, base64-encoded.
// Illustrated algorithm only; Twilio recommends its SDK validators.
export function expectedSignature(authToken, url, params) {
  let data = url;
  for (const name of Object.keys(params).sort()) data += name + params[name];
  return createHmac('sha1', authToken).update(data, 'utf8').digest('base64');
}

export function isValidSignature(authToken, header, url, params) {
  if (typeof header !== 'string' || !/^[A-Za-z0-9+/]{27}=$/.test(header)) return false;
  const received = Buffer.from(header, 'base64');
  if (received.toString('base64') !== header) return false;
  const expected = Buffer.from(expectedSignature(authToken, url, params), 'base64');
  return received.length === expected.length && timingSafeEqual(received, expected);
}

// JSON callbacks: Twilio appends a bodySHA256 query parameter carrying
// the hex SHA-256 of the raw body, and signs the URL including it.
export function bodySHA256(rawBody) {
  return createHash('sha256').update(rawBody, 'utf8').digest('hex');
}

export function isValidJsonSignature(authToken, header, urlWithBodyParam, rawBody) {
  const declared = new URL(urlWithBodyParam).searchParams.get('bodySHA256');
  if (!declared || declared !== bodySHA256(rawBody)) return false;
  return isValidSignature(authToken, header, urlWithBodyParam, {});
}

The test suite runs 18 checks: the documented worked example reproduces its published signature exactly; a genuine callback passes; a tampered field, a wrong token, an added or dropped field, a trailing-slash URL, a scheme change and a port change each fail; field sorting follows Unix case-sensitive order; malformed, empty or missing headers fail without throwing; and the JSON path accepts the genuine raw body while rejecting re-serialized or tampered bytes and a missing bodySHA256 parameter. Four encoding regressions reject invalid characters or whitespace appended to a valid signature, missing padding, and altered unused padding bits.

These are pure-function tests, not production proof. The sample has no HTTP framework integration, no token-rotation handling, no rate limiting and no monitoring. It also assumes TLS, exact external-URL configuration and middleware discipline are handled around it. In a real endpoint, signature validation runs first, payload validation second, and only then does anything touch state.

Before you expose the endpoint

Twilio's hardening guidance adds operational layers around the signature check: use a unique, unpredictable URL for each webhook endpoint rather than guessable patterns; return HTTP 200 promptly after validation and queue slow work for background workers; never log full webhook bodies; rate-limit the endpoint and monitor for unusual failure rates or traffic spikes. [SRC003]

Test the negative path deliberately, not just the happy one. Twilio provides sample code for testing your endpoint against both valid and invalid signatures; run a forged request, a replayed request and a truncated header through staging before real traffic arrives. [SRC001]

The useful launch question is not whether the demo call reached your endpoint. It is whether forged and malformed requests are rejected, genuine callbacks keep passing behind your real proxy and middleware, and replaying an already accepted callback does not repeat a business action. Signature validation handles the first check; separate durable deduplication and action-idempotency controls handle replays. The illustrative validator above does not provide those replay controls.

FAQ

Should we hand-roll signature validation like the sample?

No. Twilio explicitly recommends its SDK validation helpers, which handle URL reconstruction, HMAC computation and comparison. The sample exists to make the documented algorithm concrete and to anchor tests to Twilio's published worked example.

Does a valid signature stop replayed requests?

No. The documented scheme signs the URL and fields with no timestamp or nonce, so a captured request stays valid. Treat the signature as authenticity and integrity, and handle freshness and duplicates with your own event identity and deduplication records.

Can we allowlist Twilio's IP addresses instead?

No. Twilio states it has no fixed range of IP addresses that issue webhooks, so network allowlisting cannot replace signature validation.

Why did validation suddenly reject every real callback?

Check the URL your app reconstructs against the URL Twilio signs: trailing-slash rewrites, port differences, scheme changes after TLS termination, whitespace-trimming middleware and an unpromoted secondary Auth Token are the documented causes.

Sources

  1. Security: validating requests, the signing algorithm and its worked example - Twilio
  2. Secure webhooks: query, form and JSON body handling in validation - Twilio
  3. Webhook security: TLS, validation order and endpoint hardening - Twilio

Evidence map

  • Twilio signs webhook requests with HMAC-SHA1 over the full request URL plus POST fields sorted by name, keyed with the primary Auth Token and base64-encoded, and publishes a worked example that implementations can test against.
    Evidence: SRC001
  • For JSON callbacks, Twilio appends a bodySHA256 query parameter with the hex SHA-256 of the raw body, and validation hashes the raw body before checking the signature over the URL including that parameter.
    Evidence: SRC002
  • Without signature validation, an application is vulnerable to forged webhooks from anyone who can predict the URL; Twilio requires HTTPS for webhook endpoints and recommends SDK helpers, unique URLs, prompt responses and no full-body logging.
    Evidence: SRC003
See how CallPulse handles every call
Chat with us