class PayloadController < ApplicationController
before_action :validate_timestamp!, only: :new
before_action :validate_signature!, only: :new
def new
formatted_request = JSON.parse(request.body.read)
if formatted_request['event_name'] == 'url_verification'
render json: { challenge: request.headers['X-Gearbox-Signature'].split(',').first }, status: :ok
else
# create record
render json: :ok
end
end
private
def validate_timestamp!
timestamp = DateTime.parse(request.headers['X-Gearbox-Request-Timestamp'])
raise StandardError, 'Timestamp is invalid, possible replay attack?' unless timestamp.to_i > 5.minutes.ago.to_i
end
def validate_signature!
received_signatures = request.headers['X-Gearbox-Signature'].split(',')
timestamp = request.headers['X-Gearbox-Request-Timestamp']
formatted_request = JSON.parse(request.body.read)
signature = 'sha256=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), 'C-l2N7fVHr9gl4OgJfugcQ', "#{timestamp}:#{formatted_request}")
received_signatures.each do |received_signature|
return true if Rack::Utils.secure_compare(signature, received_signature)
end
raise StandardError, 'Signature is invalid'
end
end