Skip to content

Addition of webhook verification for Rails #17

@bnorton

Description

@bnorton

We've finalized our Partner integration for Chameleon and here is the code snippet that we use to verify the authenticity of webhooks coming from Heap!

class HeapSegments < Application
  before_action :check_signature!
  
  def create
    # queue for subsequent processing

    json_200
  end

  private

  def check_signature!
    info = request.headers['Heap-Hash'].to_s.split(/\s*,\s*/).map {|part| part.split(':') }.to_h
    timestamp = info['ts'].to_i/1000
    signature = Base64.encode64(OpenSSL::HMAC.digest('SHA256', ENV['HEAP_WEBHOOK_SECRET'], "#{info['ts']}#{request.raw_post}")).chomp

    json_403 unless timestamp > 5.seconds.ago.to_i && timestamp < 1.second.from_now.to_i
    json_403 unless ActiveSupport::SecurityUtils.secure_compare(info['hmac'], signature)
  end

end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions