Class: Twilio::Security::RequestValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/twilio-ruby/security/request_validator.rb

Constant Summary collapse

SIGNATURE_HEADER =

Header that carries the webhook signature

'X-Twilio-Signature'
SIGNATURE_SETTINGS_HEADER =

Header Twilio adds to webhooks signed with a SharedKey: key=,algorithm=

'X-Twilio-Webhooks-Signature-Settings'
HMAC_SHA1 =
'HMAC_SHA1'
HMAC_SHA256 =
'HMAC_SHA256'
DIGESTS =
{ HMAC_SHA1 => 'sha1', HMAC_SHA256 => 'sha256' }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(auth_token = nil) ⇒ RequestValidator

Initialize a Request Validator. auth_token will either be grabbed from the global Twilio object or you can pass it in here.

Parameters:

  • auth_token (String) (defaults to: nil) —

    The secret the webhook was signed with: your account auth token, or the SharedKey secret when the request carries the X-Twilio-Webhooks-Signature-Settings header

Raises:

  • (ArgumentError)


35
36
37
38
# File 'lib/twilio-ruby/security/request_validator.rb', line 35

def initialize(auth_token = nil)
  @auth_token = auth_token || Twilio.auth_token
  raise ArgumentError, 'Auth token is required' if @auth_token.nil?
end

Class Method Details

.signature_algorithm(signature_settings_header) ⇒ String

Returns the signing algorithm named in the X-Twilio-Webhooks-Signature-Settings header. A missing or empty header (or one without algorithm=) means the legacy Auth Token signature, HMAC_SHA1.

Parameters:

  • signature_settings_header (String) —

    e.g. "key=webhooks_sharedkey_...,algorithm=HMAC_SHA256"

Returns:

  • (String) —

    the algorithm name



21
22
23
24
25
26
27
# File 'lib/twilio-ruby/security/request_validator.rb', line 21

def self.signature_algorithm(signature_settings_header)
  signature_settings_header.to_s.split(',').each do |part|
    name, value = part.split('=', 2).map(&:strip)
    return value if name == 'algorithm' && !value.to_s.empty?
  end
  HMAC_SHA1
end

Instance Method Details

#build_hash_for(body) ⇒ String

Build a SHA256 hash for a body string

Parameters:

  • body (String) —

    String to hash

Returns:

  • (String) —

    A hex-encoded SHA256 of the body string



89
90
91
92
# File 'lib/twilio-ruby/security/request_validator.rb', line 89

def build_hash_for(body)
  hasher = OpenSSL::Digest.new('sha256')
  hasher.hexdigest(body)
end

#build_signature_for(url, params, algorithm = nil) ⇒ String

Build an HMAC signature for a url and parameter hash

Parameters:

  • url (String) —

    The request url, including any query parameters

  • params (#join) —

    The POST parameters

  • algorithm (String) (defaults to: nil) —

    HMAC_SHA1 (default) or HMAC_SHA256

Returns:

  • (String) —

    A base64 encoded HMAC

Raises:

  • (ArgumentError) —

    if the algorithm is not supported



103
104
105
106
107
108
109
110
# File 'lib/twilio-ruby/security/request_validator.rb', line 103

def build_signature_for(url, params, algorithm = nil)
  digest_name = digest_name_for(algorithm)
  raise ArgumentError, "Unsupported webhook signature algorithm: #{algorithm}" unless digest_name

  data = url + params.sort.join
  digest = OpenSSL::Digest.new(digest_name)
  Base64.strict_encode64(OpenSSL::HMAC.digest(digest, @auth_token, data))
end

#validate(url, params, signature, algorithm = nil) ⇒ Boolean

Validates that after hashing a request with Twilio's request-signing algorithm (https://www.twilio.com/docs/usage/security#validating-requests), the hash matches the signature parameter

Parameters:

  • url (String) —

    The url sent to your server, including any query parameters

  • params (String, Hash, #to_unsafe_h) —

    In most cases, this is the POST parameters as a hash. If you received a bodySHA256 parameter in the query string, this parameter can instead be the POST body as a string to validate JSON or other text-based payloads that aren't x-www-form-urlencoded.

  • signature (String) —

    The expected signature, from the X-Twilio-Signature header of the request

  • algorithm (String) (defaults to: nil) —

    HMAC_SHA1 (default) or HMAC_SHA256, see signature_algorithm. An unsupported algorithm fails validation and logs a warning.

Returns:

  • (Boolean) —

    whether or not the computed signature matches the signature parameter



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/twilio-ruby/security/request_validator.rb', line 53

def validate(url, params, signature, algorithm = nil)
  unless digest_name_for(algorithm)
    warn "[Twilio] Unsupported webhook signature algorithm '#{algorithm}'. " \
         "Supported: #{HMAC_SHA1}, #{HMAC_SHA256}. Upgrade twilio-ruby if Twilio added a new one."
    return false
  end

  parsed_url = URI(url)
  url_with_port = add_port(parsed_url)
  url_without_port = remove_port(parsed_url)

  valid_body = true # default succeed, since body not always provided
  params_hash = body_or_hash(params)
  unless params_hash.is_a? Enumerable
    body_hash = URI.decode_www_form(parsed_url.query || '').to_h['bodySHA256']
    params_hash = build_hash_for(params)
    valid_body = !(params_hash.nil? || body_hash.nil?) && secure_compare(params_hash, body_hash)
    params_hash = {}
  end

  # Check signature of the url with and without port numbers
  # since signature generation on the back end is inconsistent
  valid_signature_with_port = secure_compare(build_signature_for(url_with_port, params_hash, algorithm),
                                             signature)
  valid_signature_without_port = secure_compare(build_signature_for(url_without_port, params_hash, algorithm),
                                                signature)

  valid_body && (valid_signature_with_port || valid_signature_without_port)
end