Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Logentries.com HMAC Authenticator in Ruby, for Rails
# Check authenticity of a logentries.com webhook
# cf: https://logentries.com/doc/webhookalert/
# cf: https://blog.logentries.com/2013/02/webhooks-are-hmac-authenticated/
require 'openssl'
require 'base64'
require 'digest/md5'
class LogentriesAuth
attr_reader :request
def initialize(request)
@request = request
end
def authorized?
auth_sig == signature &&
auth_user == user &&
30.seconds.ago < date &&
!nonce_replay?
end
private
def canonical
[
request.method,
request.headers['Content-Type'],
Base64.encode64(Digest::MD5.digest(request.body.string)),
request.headers['Date'],
request.path,
nonce,
].map(&:strip).join("\n")
end
def signature
dg = OpenSSL::Digest.new('sha1')
Base64.encode64( OpenSSL::HMAC.digest(dg, secret, canonical)).strip
end
def date
DateTime.parse(request.headers['Date'])
end
def auth_sig
request.headers['Authorization'].split(':').last
end
def auth_user
request.headers['Authorization'].split(':').first.split.last
end
def user
ENV.fetch('LOGENTRIES_WEBHOOK_KEY', ':').split(':').first
end
def secret
ENV.fetch('LOGENTRIES_WEBHOOK_KEY', ':').split(':').last
end
def nonce
request.headers['X-Le-Nonce']
end
def nonce_replay?
return true if Redis.current.get("logentries::#{nonce}").present?
Redis.current.set("logentries::#{nonce}", 1, ex: 7.days)
false
end
end
=begin
The MIT License (MIT)
Copyright (c) 2016 PacerPro, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment