Class: RailsNexus::WebhookClient

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_nexus/webhook_client.rb

Defined Under Namespace

Classes: ValidationError

Constant Summary collapse

BLOCKED_NETWORKS =
%w[
  0.0.0.0/8 10.0.0.0/8 100.64.0.0/10 127.0.0.0/8 169.254.0.0/16
  172.16.0.0/12 192.0.0.0/24 192.0.2.0/24 192.168.0.0/16
  198.18.0.0/15 198.51.100.0/24 203.0.113.0/24 224.0.0.0/4 240.0.0.0/4
  ::/128 ::1/128 ::ffff:0:0/96 100::/64 2001:db8::/32 fc00::/7 fe80::/10 ff00::/8
].map { |network| IPAddr.new(network) }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, payload:, headers: {}, timeout: nil, resolver: nil, http_factory: nil) ⇒ WebhookClient

Returns a new instance of WebhookClient.



35
36
37
38
39
40
41
42
# File 'lib/rails_nexus/webhook_client.rb', line 35

def initialize(url:, payload:, headers: {}, timeout: nil, resolver: nil, http_factory: nil)
  @url = url.to_s
  @payload = payload
  @headers = headers || {}
  @timeout = Integer(timeout || RailsNexus.configuration.webhook_timeout || 5)
  @resolver = resolver || method(:resolve_addresses)
  @http_factory = http_factory || ->(host, port) { Net::HTTP.new(host, port) }
end

Class Method Details

.deliver(url:, payload:, headers: {}, timeout: nil) ⇒ Object



21
22
23
# File 'lib/rails_nexus/webhook_client.rb', line 21

def self.deliver(url:, payload:, headers: {}, timeout: nil)
  new(url: url, payload: payload, headers: headers, timeout: timeout).deliver
end

.redacted_url(url) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/rails_nexus/webhook_client.rb', line 25

def self.redacted_url(url)
  uri = URI.parse(url.to_s)
  return "invalid-webhook-url" if uri.host.blank?

  port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
  "#{uri.scheme}://#{uri.host}#{port}/[REDACTED]"
rescue URI::InvalidURIError
  "invalid-webhook-url"
end

Instance Method Details

#deliverObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rails_nexus/webhook_client.rb', line 44

def deliver
  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  uri, address = validated_destination
  http = build_http(uri, address)
  response = http.request(build_request(uri))
  status = response.code.to_i
  duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at

  if status.between?(300, 399)
    return failure("Webhook redirects are not allowed", status_code: response.code, duration: duration)
  end

  {
    success: status.between?(200, 299),
    status_code: response.code,
    body: response.body.to_s.truncate(500),
    duration: duration.round(3),
    error: status.between?(200, 299) ? nil : "Webhook returned HTTP #{status}"
  }
rescue ValidationError => error
  failure(error.message)
rescue StandardError
  failure("Webhook delivery failed")
end