aboutsummaryrefslogtreecommitdiff
path: root/bin/hook/fire.rb
blob: 5cd6022981578af5b35e3de89aead51a1731f5a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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)