module Telnyx::Webhook::Signature

Public Class Methods

reload_verify_key() click to toggle source
# 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) click to toggle source

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

# 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_key() click to toggle source
# File lib/telnyx/webhook.rb, line 61
def self.verify_key
  @verify_key ||= reload_verify_key
end