Skip to content
HooktierDocs

Twilio webhook signature validation fails behind a proxy

validateRequest returns false, or Twilio’s Node middleware answers 403 with Twilio Request Validation Failed. The middleware message comes from twilio-node 6.1.2. Start with the public URL, then the parameters, then the token. A load balancer that terminates TLS can leave your app rebuilding an internal HTTP URL instead of the configured HTTPS URL.

For application/x-www-form-urlencoded, Twilio signs the full URL plus the decoded POST parameter names and values. The digest is HMAC-SHA1 with the account auth token, encoded as base64, in X-Twilio-Signature.

In twilio-node 6.1.2, names use JavaScript’s UTF-16 sort order. For a repeated name, the helper sorts the distinct values in that same order and appends each name-value pair once. The form’s raw bytes are not the signed input. Reordering fields, or using + instead of %20 for the same decoded space, stays valid in the tested fixtures. Changing a decoded value fails.

For application/json, the URL includes bodySHA256. The signature covers the URL with that query parameter; a separate SHA-256 check covers the raw body. Both checks must pass. Passing JSON properties as form parameters is the wrong input. The pinned helper compares bodySHA256 against lowercase hex exactly. Uppercase or mixed-case hashes, non-hex and oversized hashes fail; the query name must be bodySHA256. This rule concerns the body hash; X-Twilio-Signature uses base64 and has no sha256= prefix.

Compare the URL configured in Twilio with the URL passed to the validator. Check the scheme, host, path, query string and trailing slash. Preserve the full query string in the URL; do not move its fields into the POST parameter map. Keep the URL in exactly the URL-encoded form Twilio requested; do not decode or re-encode it, except for the documented helper candidates below. For example, keep /webhooks%2Ftwilio rather than substituting /webhooks/twilio. The encoded path validates; the decoded path fails in the tested helper. This URL rule does not prohibit decoding POST fields.

Use a configured public URL when TLS ends at a load balancer or a tunnel uses another host. Do not derive the public URL from an arbitrary incoming Host header. Use forwarding headers only when your own trusted proxy sets them and removes client-supplied values.

For one request, compare the scheme, host, port, path and query hash at ingress and at the validator. Keep credentials and parameter values out of logs. Compare the same request at both points; another delivery does not prove what the proxy changed.

A trailing slash is significant: the tested /webhooks/twilio signature fails against /webhooks/twilio/. Twilio’s security notes also describe an index-page rewrite adding a slash. Use the public path that Twilio called.

Port and query forms accepted by Node 6.1.2

Section titled “Port and query forms accepted by Node 6.1.2”

The pinned helper parses the request URL with WHATWG URL and tries four candidates:

  1. The URL with its port removed.
  2. The URL with its explicit port kept, or its default port added (443 for HTTPS, 80 for HTTP).
  3. The first URL with the query parsed and re-encoded by Node’s legacy querystring module.
  4. The second URL with that legacy query form.

The legacy form groups repeated query names and re-encodes decoded names and values. Its WHATWG reparse can remove a default port again. These are helper behaviours at this pin, not permission to substitute another host, scheme or path.

URL used to sign URL passed to the verifier Observed result at the pin
HTTPS without a port Same URL with :443 Valid
HTTPS with :443 Same URL without a port Valid
HTTPS without a port Same URL with :90 Valid: the helper also removes the port
HTTPS with :90 Same URL without a port Invalid: the helper only adds the default port
HTTPS with :90 Same URL with :90 Valid
HTTPS Same host and path over HTTP Invalid
URL with a query string Same URL with the query dropped Invalid

These rows were run through validateRequest before recording their expected results. The fixtures also exercise a query with spaces and interleaved repeated names.

2. You pass only a fixed set of parameters

Section titled “2. You pass only a fixed set of parameters”

Twilio can introduce new parameters without advance notice. Pass every received form parameter to the SDK, including repeated values. Do not construct a fixed list such as only From, To and Body. Do not trim decoded values before validation.

Query fields remain in the URL. Form fields go in the parameter map. This separation also keeps form reordering from becoming a false diagnosis.

Keep the URL’s bodySHA256 query parameter and pass the original body to validateRequestWithBody. Do not parse and re-serialize JSON before hashing it.

For the same JSON request, compare the raw body length and SHA-256 immediately before and after a suspected proxy or parser. A byte change can leave the URL signature valid while the body hash fails. The changed-body fixture adds one space and is invalid.

Twilio’s security notes require the primary AuthToken. A newly created secondary token does not become the signing key until it is promoted. Check which primary token the running process actually reads after a rotation. Reject an empty token before calling the helper.

Do not infer a webhook signing credential from successful REST API authentication. The subaccounts page describes REST credentials, but does not establish the webhook signing token for a subaccount callback. Verify that account context before changing the credential.

5. Basic authentication credentials remain in the signed URL

Section titled “5. Basic authentication credentials remain in the signed URL”

For the HTTP and HTTPS SMS/voice callbacks listed in its security notes, Twilio removes the username and password before computing the signature. Use a validation URL without that user information, even when the configured fetch URL uses Basic authentication.

The pinned Node helper itself retains user information while building its URL candidates. Do not expect it to strip those credentials for you. Keep credentials out of diagnostic logs.

Twilio recommends its SDK helpers for application validation. The Express sample uses the pinned helper. The Go sample makes the signed inputs visible for diagnosis.

Pass authToken from secure configuration and publicUrl from the public endpoint configuration, including the query string. This example handles form requests only. The adapter tests mixed-case signature header names.

This route is a validation probe. It discards the request and reports only the validation status. Before using it for business events, replace its success response with durable storage or enqueueing, then answer, then process asynchronously. If storage fails, return an error instead of reporting acceptance.

express-twilio.mjs
import express from 'express';
import twilio from 'twilio';
// Validation probe only. A production handler must store verified work before answering.
export function validationProbe(authToken, publicUrl) {
const app = express();
app.post('/webhooks/twilio', express.raw({ type: 'application/x-www-form-urlencoded' }), (req, res) => {
const signature = req.get('X-Twilio-Signature');
if (!signature) return res.sendStatus(400);
if (!authToken || !/^[A-Za-z0-9+/]{27}=$/.test(signature)) return res.sendStatus(403);
const digest = Buffer.from(signature, 'base64');
if (digest.length !== 20 || digest.toString('base64') !== signature) return res.sendStatus(403);
if (!req.is('application/x-www-form-urlencoded') || !Buffer.isBuffer(req.body)) return res.sendStatus(403);
try {
const body = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(req.body);
const params = Object.create(null);
for (const [name, value] of new URLSearchParams(body)) (params[name] ??= []).push(value);
if (!twilio.validateRequest(authToken, signature, publicUrl, params)) {
return res.sendStatus(403);
}
} catch {
return res.sendStatus(403);
}
return res.sendStatus(204);
});
return app;
}

Pass the configured public URL, including its query string, and the auth token from secure configuration. This form-only probe strictly decodes raw UTF-8 and preserves repeated and blank values through MultiDict. It returns 400 for a missing signature, 403 for invalid input and 204 for a valid signature. Before using it for business events, durably store or enqueue verified work before answering, then process asynchronously. Return an error when storage fails.

twilio-python 9.8.3 differs from twilio-node 6.1.2 on three tested fixtures: extra-legacy-query, extra-utf16-order and extra-repeated-values are invalid in Python and valid in Node. Python sorts parameter names and distinct values by Python string order, and tries port variants without Node’s legacy-query candidates (source lines 65–86, 105–137). The separate python-sdk scenario group records those SDK results and the six required signature cases. It does not claim full T13 parity.

twilio_flask.py
import base64
import binascii
from urllib.parse import parse_qsl
from flask import Flask, request
from werkzeug.datastructures import MultiDict
from twilio.request_validator import RequestValidator
def validation_probe(auth_token, public_url):
app = Flask(__name__)
# Validation probe only. Store verified work before answering in production.
@app.post("/webhooks/twilio")
def receive():
signature = request.headers.get("X-Twilio-Signature", "")
if not signature:
return "", 400
if not auth_token:
return "", 403
try:
digest = base64.b64decode(signature, validate=True)
except (binascii.Error, ValueError):
return "", 403
if len(digest) != 20 or base64.b64encode(digest).decode("ascii") != signature:
return "", 403
if request.mimetype != "application/x-www-form-urlencoded":
return "", 403
try:
body = request.get_data().decode("utf-8", errors="strict")
params = MultiDict(parse_qsl(body, keep_blank_values=True, errors="strict"))
except (UnicodeError, ValueError):
return "", 403
if not RequestValidator(auth_token).validate(public_url, params, signature):
return "", 403
return "", 204
return app

Read the received bytes first. Pass those unchanged as a Go string to VerifyTwilio, along with the full public URL, media type without parameters and signature header. The function rejects invalid UTF-8 and preserves a BOM. Do not pass text produced by lossy decoding. For Node decoding, use TextDecoder with fatal: true and ignoreBOM: true, as above.

This Go sample covers canonical ASCII HTTP(S) URLs only. It fails closed with invalid for dot segments, encoded dot segments and URLs whose re-serialization changes the input. Hosts must use lowercase [a-z0-9-] labels separated by dots, or canonical dotted-quad IPv4. Ports must be empty or use canonical decimal values from 1 to 65535; leading zeros and abbreviated IPv4 are rejected. It does not implement full WHATWG normalization or internationalized hosts. The Go-only regression group rejects /a/../webhooks/twilio, although Node accepts its normalized path. The documented port candidates remain supported.

The function returns missing for an absent header and invalid for a malformed header, empty token or mismatch. The comparison uses hmac.Equal.

Imports: crypto/hmac, crypto/sha1, crypto/sha256, encoding/base64, encoding/hex, fmt, net/url, slices, strconv, strings and unicode/utf8.

verify-twilio.go
// VerifyTwilio follows the twilio-node 6.1.2 URL variants, not raw form-body signing.
func VerifyTwilio(token, signature, requestURL, contentType, body string) string {
if signature == "" {
return "missing"
}
if token == "" || !utf8.ValidString(body) {
return "invalid"
}
decoded, err := base64.StdEncoding.Strict().DecodeString(signature)
if err != nil || len(decoded) != sha1.Size || base64.StdEncoding.EncodeToString(decoded) != signature {
return "invalid"
}
forms, err := twilioURLForms(requestURL)
if err != nil {
return "invalid"
}
params, ok := twilioParams(forms[0], contentType, body)
if !ok {
return "invalid"
}
suffix := twilioParamSuffix(params)
matched := false
for _, form := range forms {
mac := hmac.New(sha1.New, []byte(token))
_, _ = mac.Write([]byte(form + suffix))
if hmac.Equal(decoded, mac.Sum(nil)) {
matched = true
}
}
if matched {
return "valid"
}
return "invalid"
}
func twilioParams(requestURL, contentType, body string) (url.Values, bool) {
switch contentType {
case "application/json":
u, err := url.Parse(requestURL)
if err != nil {
return nil, false
}
hash := sha256.Sum256([]byte(body))
for field := range strings.SplitSeq(u.RawQuery, "&") {
name, value := twilioFormPair(field)
if name == "bodySHA256" {
return url.Values{}, hmac.Equal([]byte(value), []byte(hex.EncodeToString(hash[:])))
}
}
return nil, false
case "application/x-www-form-urlencoded":
params := url.Values{}
for field := range strings.SplitSeq(body, "&") {
if field != "" {
name, value := twilioFormPair(field)
params.Add(name, value)
}
}
return params, true
default:
return nil, false
}
}
func twilioFormPair(field string) (string, string) {
name, value, _ := strings.Cut(field, "=")
return formDecode(name), formDecode(value)
}
func twilioParamSuffix(params url.Values) string {
names := make([]string, 0, len(params))
for name := range params {
names = append(names, name)
}
slices.SortFunc(names, utf16Order)
var suffix strings.Builder
for _, name := range names {
values := slices.Clone(params[name])
slices.SortFunc(values, utf16Order)
for _, value := range slices.Compact(values) {
suffix.WriteString(name)
suffix.WriteString(value)
}
}
return suffix.String()
}
// JavaScript sorts UTF-16 code units; UTF-8 byte sorting differs for astral characters.
func utf16Order(a, b string) int {
units := func(s string) []int {
result := []int{}
for _, r := range s {
if r > 0xffff {
r -= 0x10000
result = append(result, 0xd800+int(r>>10), 0xdc00+int(r&1023))
} else {
result = append(result, int(r))
}
}
return result
}
return slices.Compare(units(a), units(b))
}
func twilioURLForms(raw string) ([]string, error) {
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("parse public URL: %w", err)
}
if !canonicalTwilioURL(raw, u) {
return nil, fmt.Errorf("public URL must be canonical ASCII HTTP(S), without dot segments")
}
u.Scheme = strings.ToLower(u.Scheme)
if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return nil, fmt.Errorf("public URL requires HTTP(S) and a host")
}
u.Host = strings.ToLower(u.Host)
if u.Path == "" {
u.Path = "/"
}
// WHATWG special-URL query encoding preserves escapes and encodes literal spaces/apostrophes.
u.RawQuery = strings.ReplaceAll(strings.ReplaceAll(u.RawQuery, " ", "%20"), "'", "%27")
port := u.Port()
if port == "" {
port = twilioDefaultPort(u.Scheme)
}
hostname := u.Hostname()
if strings.Contains(hostname, ":") {
hostname = "[" + hostname + "]"
}
without := *u
without.Host = hostname
with := *u
with.Host = hostname + ":" + port
forms := []string{without.String(), with.String()}
for _, form := range slices.Clone(forms) {
legacy, err := legacyTwilioQuery(form)
if err != nil {
return nil, err
}
forms = append(forms, legacy)
}
return forms, nil
}
func twilioDigits(s string) bool {
if s == "" {
return false
}
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
func canonicalTwilioIPv4(labels []string) bool {
if len(labels) != 4 {
return false
}
for _, label := range labels {
n, err := strconv.Atoi(label)
if err != nil || n < 0 || n > 255 || strconv.Itoa(n) != label {
return false
}
}
return true
}
func canonicalTwilioHostname(host string) bool {
if host == "" {
return false
}
for label := range strings.SplitSeq(host, ".") {
if label == "" {
return false
}
for _, c := range label {
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' {
return false
}
}
}
return true
}
func canonicalTwilioPort(port string) bool {
if port == "" {
return true
}
n, err := strconv.Atoi(port)
return err == nil && n >= 1 && n <= 65535 && strconv.Itoa(n) == port
}
func canonicalTwilioAuthority(u *url.URL) bool {
host, port := u.Hostname(), u.Port()
if !canonicalTwilioHostname(host) || !canonicalTwilioPort(port) {
return false
}
authority := host
if port != "" {
authority += ":" + port
}
if u.Host != authority {
return false
}
// WHATWG treats a numeric final label as IPv4, including abbreviated and hex spellings.
labels := strings.Split(host, ".")
if last := labels[len(labels)-1]; twilioDigits(last) || strings.HasPrefix(last, "0x") {
if !canonicalTwilioIPv4(labels) {
return false
}
}
return true
}
func canonicalTwilioURL(raw string, u *url.URL) bool {
if !canonicalTwilioAuthority(u) {
return false
}
if u.String() != raw || u.Scheme != strings.ToLower(u.Scheme) || u.Host != strings.ToLower(u.Host) || u.Path == "" || strings.ContainsAny(raw, "\\ \t\r\n'") {
return false
}
for _, c := range raw {
if c < 0x21 || c > 0x7e {
return false
}
}
for segment := range strings.SplitSeq(u.EscapedPath(), "/") {
segment = strings.ReplaceAll(strings.ToLower(segment), "%2e", ".")
if segment == "." || segment == ".." {
return false
}
}
return true
}
func twilioDefaultPort(scheme string) string {
if scheme == "https" {
return "443"
}
return "80"
}
func legacyTwilioQuery(raw string) (string, error) {
u, err := url.Parse(raw)
if err != nil {
return "", fmt.Errorf("parse legacy URL: %w", err)
}
if u.RawQuery == "" {
return raw, nil
}
// The helper reparses with WHATWG URL, which removes an explicit default port.
if (u.Scheme == "https" && u.Port() == "443") || (u.Scheme == "http" && u.Port() == "80") {
u.Host = strings.TrimSuffix(u.Host, ":"+u.Port())
}
names, values := legacyQueryParams(u.RawQuery)
// querystring.stringify uses Object.keys: array-index names precede other names.
slices.SortStableFunc(names, legacyNameOrder)
fields := []string{}
for _, name := range names {
for _, value := range values[name] {
fields = append(fields, legacyEscape(name)+"="+legacyEscape(value))
}
}
u.RawQuery = ""
u.ForceQuery = false
return u.String() + "?" + strings.Join(fields, "&"), nil
}
func legacyQueryParams(query string) ([]string, map[string][]string) {
names := []string{}
values := map[string][]string{}
i := 0
for field := range strings.SplitSeq(query, "&") {
if i >= 1000 {
break
} // Node querystring.parse's default maximum.
i++
if field == "" {
continue
}
name, value := twilioFormPair(field)
if _, exists := values[name]; !exists {
names = append(names, name)
}
values[name] = append(values[name], value)
}
return names, values
}
func legacyArrayIndex(s string) (uint64, bool) {
n, err := strconv.ParseUint(s, 10, 32)
return n, err == nil && n < 4294967295 && strconv.FormatUint(n, 10) == s
}
func legacyNameOrder(a, b string) int {
ai, aok := legacyArrayIndex(a)
bi, bok := legacyArrayIndex(b)
switch {
case aok && bok && ai < bi:
return -1
case aok && bok && ai > bi:
return 1
case aok && bok:
return 0
case aok:
return -1
case bok:
return 1
default:
return 0
}
}
func legacyEscape(s string) string {
const digits = "0123456789ABCDEF"
var out strings.Builder
for _, b := range []byte(s) {
if (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || strings.ContainsRune("-_.!~*'()", rune(b)) {
out.WriteByte(b)
} else {
out.WriteByte('%')
out.WriteByte(digits[b>>4])
out.WriteByte(digits[b&15])
}
}
return out.String()
}
// Form decoding tolerates stray percent signs, as URLSearchParams does.
func formDecode(s string) string {
s = strings.ReplaceAll(s, "+", " ")
decoded := []byte{}
for i := 0; i < len(s); i++ {
if s[i] == '%' && i+2 < len(s) {
pair, err := hex.DecodeString(s[i+1 : i+3])
if err == nil {
decoded = append(decoded, pair[0])
i += 2
continue
}
}
decoded = append(decoded, s[i])
}
var result strings.Builder
for len(decoded) > 0 {
r, n := utf8.DecodeRune(decoded)
if r == utf8.RuneError && n == 1 {
n = maximalUTF8Subpart(decoded)
}
result.WriteRune(r)
decoded = decoded[n:]
}
return result.String()
}
// Consume a valid incomplete UTF-8 prefix as one WHATWG replacement character.
func maximalUTF8Subpart(decoded []byte) int {
first := decoded[0]
width := 0
switch {
case first >= 0xc2 && first <= 0xdf:
width = 2
case first >= 0xe0 && first <= 0xef:
width = 3
case first >= 0xf0 && first <= 0xf4:
width = 4
}
n := 1
for n < width && n < len(decoded) {
if !utf8Continuation(first, decoded[n], n) {
break
}
n++
}
return n
}
func utf8Continuation(first, b byte, position int) bool {
if b < 0x80 || b > 0xbf {
return false
}
if position != 1 {
return true
}
switch first {
case 0xe0:
return b >= 0xa0
case 0xed:
return b <= 0x9f
case 0xf0:
return b >= 0x90
case 0xf4:
return b <= 0x8f
default:
return true
}
}

The documented example uses the test token 12345 and produces L/OH5YylLD5NRKLltdqwSvS0BnU=. The verifier passes that example, reordered and re-encoded forms, repeated values, UTF-16 ordering, the port cases, legacy queries and the JSON hash cases. An empty-key forged signature is rejected by the samples’ explicit token guard.

  1. Use the public URL, including scheme, host, path and query string.
  2. Remove Basic authentication user information from the validation URL.
  3. Pass every decoded form field, preserving repeated values and whitespace.
  4. For JSON, keep bodySHA256 and hash the original body.
  5. Use the verified primary auth token and reject an empty value.
  6. Check the signature header at ingress and in the app for the same request.
  7. Compare the same request’s inputs before and after the suspected layer.

A matching pasted fixture proves that its inputs match. It does not prove what a live proxy changed. Keep the measurements from the live request when diagnosing that boundary.

Checked on 2026-11-08.

  • Twilio: Security, sections “Validating requests are coming from Twilio”, “Explore the algorithm yourself” and “A few notes”: algorithm, documented example, primary token, trailing slash and Basic authentication URL rules.
  • Twilio: Webhooks security, sections “Authenticate with signatures” and “Understand parameters in signature validation”: evolving fields, query/form separation and raw JSON body hashing.
  • Twilio: Subaccounts, section “Authentication”: REST credentials; it does not specify a subaccount webhook signing credential.
  • twilio-node 6.1.2, commit de6edf89c937b87dd155b6f1ca9b659ae4dab54d: src/webhooks/webhooks.ts, lines 68–118 (URL forms), 127–166 (sorting and HMAC), 189–245 (validateRequest), 173–178 and 263–292 (body hash), 313–329 (public URL override) and 462–469 (middleware failure).
  • twilio-python 9.8.3: twilio/request_validator.py, lines 65–98 (sorting and Flask repeated values) and 105–137 (URL candidates).