Skip to content

Commit

Permalink
Update verify_webhook_signature to match more recent security guideli…
Browse files Browse the repository at this point in the history
  • Loading branch information
rick authored Nov 9, 2021
1 parent ef24854 commit b429a0c
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions template_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,29 +118,28 @@ def authenticate_installation(payload)
@installation_client = Octokit::Client.new(bearer_token: @installation_token)
end

# Check X-Hub-Signature to confirm that this webhook was generated by
# Check X-Hub-Signature-256 to confirm that this webhook was generated by
# GitHub, and not a malicious third party.
#
# GitHub uses the WEBHOOK_SECRET, registered to the GitHub App, to
# create the hash signature sent in the `X-HUB-Signature` header of each
# create the hash signature sent in the `X-HUB-Signature-256` header of each
# webhook. This code computes the expected hash signature and compares it to
# the signature sent in the `X-HUB-Signature` header. If they don't match,
# the signature sent in the `X-HUB-Signature-256` header. If they don't match,
# this request is an attack, and you should reject it. GitHub uses the HMAC
# hexdigest to compute the signature. The `X-HUB-Signature` looks something
# like this: "sha1=123456".
# See https://developer.github.com/webhooks/securing/ for details.
# hexdigest to compute the signature. The `X-HUB-Signature-256` looks something
# like this: "sha256=123456".
# See https://docs.github.com/en/developers/webhooks-and-events/webhooks/securing-your-webhooks for details.
def verify_webhook_signature
their_signature_header = request.env['HTTP_X_HUB_SIGNATURE'] || 'sha1='
their_signature_header = request.env['HTTP_X_HUB_SIGNATURE_256'] || 'sha256='
method, their_digest = their_signature_header.split('=')
our_digest = OpenSSL::HMAC.hexdigest(method, WEBHOOK_SECRET, @payload_raw)
halt 401 unless their_digest == our_digest
our_digest = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), WEBHOOK_SECRET, @payload_raw)
halt 401 unless Rack::Utils.secure_compare(their_digest, our_digest)

# The X-GITHUB-EVENT header provides the name of the event.
# The action value indicates the which action triggered the event.
logger.debug "---- received event #{request.env['HTTP_X_GITHUB_EVENT']}"
logger.debug "---- action #{@payload['action']}" unless @payload['action'].nil?
end

end

# Finally some logic to let us run this server directly from the command line,
Expand Down

0 comments on commit b429a0c

Please sign in to comment.