Module: Telnyx::Webhook::Signature

Defined in:
lib/telnyx/webhook.rb

Class Method Summary collapse

Class Method Details

.reload_verify_keyObject



65
66
67
# File 'lib/telnyx/webhook.rb', line 65

def self.reload_verify_key
  @verify_key = Ed25519::VerifyKey.new(Base64.decode64(ENV.fetch("TELNYX_PUBLIC_KEY")))
end

.verify(payload, signature_header, timestamp, tolerance: nil) ⇒ Object

Verifies the signature for a given payload.

Raises a SignatureVerificationError in the following cases:

  • the signature does not match the expected format

  • no signatures found

  • a tolerance is provided and the timestamp is not within the tolerance

Returns true otherwise



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/telnyx/webhook.rb', line 37

def self.verify(payload, signature_header, timestamp, tolerance: nil)
  signature = Base64.decode64(signature_header)
  timestamp = timestamp.to_i
  signed_payload = "#{timestamp}|#{payload}"

  if tolerance && timestamp < Time.now.to_f - tolerance
    raise SignatureVerificationError.new(
      "Timestamp outside the tolerance zone (#{Time.at(timestamp)})",
      signature_header, http_body: payload
    )
  end

  begin
    verify_key.verify(signature, signed_payload)
  rescue Ed25519::VerifyError
    raise SignatureVerificationError.new(
      "Signature is invalid and does not match the payload",
      signature, http_body: payload
    )
  end

  true
end

.verify_keyObject



61
62
63
# File 'lib/telnyx/webhook.rb', line 61

def self.verify_key
  @verify_key ||= reload_verify_key
end