Module: Fopost::Rails::WebhookSignature

Defined in:
lib/fopost/rails/webhook_signature.rb

Overview

FoPost signs every webhook body with HMAC-SHA256 over the exact bytes it sent, keyed by the webhook secret, and puts the hex digest in X-FoPost-Signature behind a sha256= prefix.

Verify against the raw request body — a parsed-and-re-serialized hash will not match.

Constant Summary collapse

SIGNATURE_HEADER =
'X-FoPost-Signature'
EVENT_HEADER =
'X-FoPost-Event'
DELIVERY_HEADER =
'X-FoPost-Delivery'
PREFIX =
'sha256='

Class Method Summary collapse

Class Method Details

.sign(payload, secret) ⇒ Object

The header value FoPost would send for this body and secret.



21
22
23
# File 'lib/fopost/rails/webhook_signature.rb', line 21

def self.sign(payload, secret)
  "#{PREFIX}#{OpenSSL::HMAC.hexdigest('SHA256', secret.to_s, payload.to_s)}"
end

.valid?(payload, signature, secret) ⇒ Boolean

Constant-time comparison, so a wrong signature leaks no timing.

Returns:

  • (Boolean)


26
27
28
29
30
# File 'lib/fopost/rails/webhook_signature.rb', line 26

def self.valid?(payload, signature, secret)
  return false if signature.nil? || secret.nil? || secret.to_s.empty?

  ActiveSupport::SecurityUtils.secure_compare(sign(payload, secret), signature.to_s)
end