Class: Fintoc::WebhookSignature

Inherits:
Object
  • Object
show all
Defined in:
lib/fintoc/webhook_signature.rb

Constant Summary collapse

EXPECTED_SCHEME =
'v1'
DEFAULT_TOLERANCE =

5 minutes

300

Class Method Summary collapse

Class Method Details

.compute_signature(payload, timestamp, secret) ⇒ Object



32
33
34
35
# File 'lib/fintoc/webhook_signature.rb', line 32

def compute_signature(payload, timestamp, secret)
  signed_payload = "#{timestamp}.#{payload}"
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret, signed_payload)
end

.verify_header(payload, header, secret, tolerance = DEFAULT_TOLERANCE) ⇒ Object

rubocop:disable Naming/PredicateMethod



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/fintoc/webhook_signature.rb', line 13

def verify_header(payload, header, secret, tolerance = DEFAULT_TOLERANCE) # rubocop:disable Naming/PredicateMethod
  timestamp, signatures = parse_header(header)

  verify_timestamp(timestamp, tolerance) if tolerance

  expected_signature = compute_signature(payload, timestamp, secret)
  signature = signatures[EXPECTED_SCHEME]

  if signature.nil? || signature.empty? # rubocop:disable Rails/Blank
    raise Fintoc::Errors::WebhookSignatureError.new("No #{EXPECTED_SCHEME} signature found")
  end

  unless same_signatures?(signature, expected_signature)
    raise Fintoc::Errors::WebhookSignatureError.new('Signature mismatch')
  end

  true
end