Class: MessageBird::RequestValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/messagebird/request_validator.rb

Overview

RequestValidator validates request signature signed by MessageBird services.

Constant Summary collapse

ALLOWED_ALGOS =
%w[HS256 HS384 HS512].freeze

Instance Method Summary collapse

Constructor Details

#initialize(signature_key, skip_url_validation: false) ⇒ RequestValidator

Returns a new instance of RequestValidator.

Parameters:

  • signature_key (string)

    customer signature key. Can be retrieved through <a href=“dashboard.messagebird.com/developers/settings”>Developer Settings</a>. This is NOT your API key.

  • skip_url_validation (bool) (defaults to: false)

    whether url_hash claim validation should be skipped. Note that when true, no query parameters should be trusted.



23
24
25
26
# File 'lib/messagebird/request_validator.rb', line 23

def initialize(signature_key, skip_url_validation: false)
  @signature_key = signature_key
  @skip_url_validation = skip_url_validation
end

Instance Method Details

#validate_signature(signature, url, request_body) ⇒ Array

This method validates provided request signature, which is a JWT token. This JWT is signed with a MessageBird account unique secret key, ensuring the request is from MessageBird and a specific account. The JWT contains the following claims:

*   "url_hash" - the raw URL hashed with SHA256 ensuring the URL wasn't altered.
*    "payload_hash" - the raw payload hashed with SHA256 ensuring the payload wasn't altered.
*    "jti" - a unique token ID to implement an optional non-replay check (NOT validated by default).
*    "nbf" - the not before timestamp.
*    "exp" - the expiration timestamp is ensuring that a request isn't captured and used at a later time.
*    "iss" - the issuer name, always MessageBird.

Parameters:

  • signature (String)

    the actual signature taken from request header “MessageBird-Signature-JWT”.

  • url (String)

    the raw url including the protocol, hostname and query string, e.g. “example.com/?example=42”.

  • request_body (Array)

    the raw request body.

Returns:

  • (Array)

    raw signature payload

Raises:

See Also:



44
45
46
47
48
49
50
51
52
53
# File 'lib/messagebird/request_validator.rb', line 44

def validate_signature(signature, url, request_body)
  raise ValidationError, 'Signature can not be empty' if signature.to_s.empty?
  raise ValidationError, 'URL can not be empty' if !@skip_url_validation && url.to_s.empty?

  claims = decode_signature signature
  validate_url(url, claims['url_hash']) unless @skip_url_validation
  validate_payload(request_body, claims['payload_hash'])

  claims
end