diff options
Diffstat (limited to 'bin/hook/fire.rb')
-rwxr-xr-x | bin/hook/fire.rb | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/bin/hook/fire.rb b/bin/hook/fire.rb new file mode 100755 index 0000000..5cd6022 --- /dev/null +++ b/bin/hook/fire.rb @@ -0,0 +1,54 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# bin/hook/fire.rb: trigger deploy webhook. +# +# Requires that the following environment variables are set: +# +# * HOOK_URL: Webhook URL +# * HOOK_HMAC_KEY: Hook HMAC-SHA256 key. +# + +require 'openssl' +require 'json' +require 'time' +require 'uri' +require 'net/http' +require 'pp' + +# get hook URL and HMAC key +hook_url = ENV.fetch('HOOK_URL') +key = ENV.fetch('HOOK_HMAC_KEY') + +# get name of HMAC header, or default to X-Hub-Signature if unspecified +header_name = ENV.fetch('HOOK_HMAC_HEADER', 'X-Hub-Signature') + +# build body +body = JSON({ + # current timestamp, in ISO8601/RFC3339 format + time: Time.now.iso8601, + + # random nonce + nonce: OpenSSL::Digest::SHA256.hexdigest(OpenSSL::Random.random_bytes(32)), +}) + +# calculate hmac +hmac = OpenSSL::HMAC.hexdigest('SHA256', key, body) + +# parse uri +uri = URI.parse(hook_url) + +# build request +req = Net::HTTP::Post.new(uri.path) +# req[header_name] = hmac +req[header_name] = 'sha256=%s' % [hmac] +req['Content-Type'] = 'application/json' +req.body = body + +# build connection +http = Net::HTTP.new(uri.host, uri.port) +http.use_ssl = true + +# send request +pp http.request(req) |