munster 0.3.1 → 0.4.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 70c4c7bb98c04fb6e5d429ac03cd9dd8734e8a8d55d8934a1eb41d1a4e359aec
4
- data.tar.gz: 4d2ec2780fe9900c61512b2cdeb7c70351ec8a80d69bf4a23734e600b69d3a83
3
+ metadata.gz: 7d3f84bd06c033ef585c3282701915793b981142351824cc7bba2f41c5bcde4b
4
+ data.tar.gz: 9e614a61681b3bed5667905ae378a357fcfa96d85c79b7d85c32473c2b763c4f
5
5
  SHA512:
6
- metadata.gz: bb7319560e29abf5011b73e595cba880100402ff03713d9b4d051c8d06b27ff17591703f077f5c5366d2824cf8d8ec4fab93bc72fb74b8c4517215a4aea5e5e2
7
- data.tar.gz: 0712b43343c58e637d90c4171de3b9e4c5cd8c96815d3afa84ccdf7718ccf3115cc7a2ec2ee552878c88ec307c021b9e9d905dff0e345f29aca18de55683b92f
6
+ metadata.gz: 616dc8e6585239309106444bb65de90d572e946e08479044459e5f8deb764d0d308d22da895152e3d7250345a81640f627ea72485daf17d6d51b03299d29f5c3
7
+ data.tar.gz: 369a9b8ce33c83e876836f652b57fc618a82e3028818531f6bc98d8732fad53cc7a926d6faf2ad8711c5e08ac3e0c9ec23de06a95b597087f86091dfb78e6240
data/CHANGELOG.md CHANGED
@@ -3,31 +3,37 @@ All notable changes to this project will be documented in this file.
3
3
 
4
4
  This format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
- ## 0.3.1
6
+ ## 0.4.1
7
+
8
+ - Webhook processor now requires `active_job/railtie`, instead of `active_job`. It requires GlobalID to work and that get's required only with railtie.
9
+ - Adding a state transition from `error` to `received`. Proccessing job will be enqueued automatic after this transition was executed.
10
+
11
+ ## 0.4.0
7
12
 
8
- ### Changed
13
+ - Limit the size of the request body, since otherwise there can be a large attack vector where random senders can spam the database with data and cause a denial of service. With background validation, this is one of the few cases where we want to reject the payload without persisting it.
14
+ - Manage the `state` of the `ReceivedWebhook` from the background job itself. This frees up the handler to actually do the work associated with processing only. The job will manage the rest.
15
+ - Use `valid?` in the background job instead of the controller. Most common configuration issue is an incorrectly specified signing secret, or an incorrectly implemented input validation. When these happen, it is better to allow the webhook to be reprocessed
16
+ - Use instance methods in handlers instead of class methods, as they are shorter to define. Assume a handler module supports `.new` - with a module using singleton methods it may return `self` from `new`.
17
+ - In the config, allow the handlers specified as strings. Module resolution in Rails happens after the config gets loaded, because the config may alter the Zeitwerk load paths. To allow the config to get loaded and to allow handlers to be autoloaded using Zeitwerk, the handler modules have to be resolved lazily. This also permits the handlers to be reloadable, like any module under Rails' autoloading control.
18
+ - Simplify the Rails app used in tests to be small and keep it in a single file
19
+ - If a handler is willing to expose errors to the caller, let Rails rescue the error and display an error page or do whatever else is configured for Rails globally.
20
+ - Store request headers with the received webhook to allow for async validation. Run `bin/rails g munster:install` to add the required migration.
21
+
22
+ ## 0.3.1
9
23
 
10
24
  - BaseHandler#expose_errors_to_sender? default to true now.
11
25
 
12
26
  ## 0.3.0
13
27
 
14
- ### Changed
15
28
  - state_machine_enum library was moved in it's own library/gem.
16
-
17
- ### Fixed
18
29
  - Provide handled: true attribute for Rails.error.report method, because it is required in Rails 7.0.
19
30
 
20
31
  ## 0.2.0
21
32
 
22
- ### Changed
23
-
24
33
  - Handler methods are now defined as instance methods for simplicity.
25
34
  - Define service_id in initializer with active_handlers, instead of handler class.
26
35
  - Use ruby 3.0 as a base for standard/rubocop, format all code according to it.
27
-
28
- ### Added
29
-
30
- - Introduce Rails common error reporter ( https://guides.rubyonrails.org/error_reporting.html )
36
+ - Use Rails common error reporter ( https://guides.rubyonrails.org/error_reporting.html )
31
37
 
32
38
  ## 0.1.0
33
39
 
data/README.md CHANGED
@@ -2,9 +2,11 @@
2
2
 
3
3
  Munster is a Rails engine that provides a webhook endpoint for receiving and processing webhooks from various services. Engine stores received webhook first and later processes webhook in a separete async process.
4
4
 
5
- Source code is extracted from https://cheddar.me/ main service to be used in internal microservices. Code here could be a subject to change while we flesh out details.
6
-
7
- Due to that, support for this gem is limited.
5
+ > [!CAUTION]
6
+ > At the moment Munster is only used internally at Cheddar. Any support to external parties is on best-effort
7
+ > basis. While we are happy to see issues and pull requests, we can't guarantee that those will be addressed
8
+ > quickly. The engine does receive rapid updates which may break your application if you come to depend on
9
+ > the library. That is to be expected.
8
10
 
9
11
  ## Installation
10
12
 
@@ -20,11 +22,25 @@ If bundler is not being used to manage dependencies, install the gem by executin
20
22
 
21
23
  Generate migrations and initializer file.
22
24
 
23
- `munster:install`
25
+ `bin/rails g munster:install`
24
26
 
25
27
  Mount munster engine in your routes.
26
28
 
27
- `mount Munster::Engine, at: "/webhooks"`
29
+ ```ruby
30
+ mount Munster::Engine, at: "/webhooks"
31
+ ```
32
+
33
+ Define a class for your first handler (let's call it `ExampleHandler`) and inherit it from `Munster::BaseHandler`. Place it somewhere where Rails autoloading can find it, and add it to your `munster.rb` config file:
34
+
35
+ ```ruby
36
+ config.active_handlers = {
37
+ "example" => "ExampleHandler"
38
+ }
39
+ ```
40
+
41
+ ## Example handlers
42
+
43
+ We provide a number of webhook handlers which demonstrate certain features of Munster. You will find them in `handler-examples`.
28
44
 
29
45
  ## Requirements
30
46
 
@@ -38,7 +54,8 @@ This project depends on two dependencies:
38
54
  This gem uses [Rails common error reporter](https://guides.rubyonrails.org/error_reporting.html) to report any possible error to services like Honeybadger, Appsignal, Sentry and etc. Most of those services already support this common interface, if not - it's not that hard to add this support on your own.
39
55
 
40
56
  It's possible to provide additional context for every error. e.g.
41
- ```
57
+
58
+ ```ruby
42
59
  Munster.configure do |config|
43
60
  config.error_context = { appsignal: { namespace: "webhooks" } }
44
61
  end
data/Rakefile CHANGED
@@ -1,12 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "bundler/setup"
4
-
5
- APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__)
6
- load "rails/tasks/engine.rake"
7
-
8
- load "rails/tasks/statistics.rake"
9
-
4
+ require "rake/testtask"
10
5
  require "bundler/gem_tasks"
11
6
  require "standard/rake"
12
7
 
@@ -15,4 +10,17 @@ task :format do
15
10
  `bundle exec magic_frozen_string_literal .`
16
11
  end
17
12
 
18
- task default: %i[standard]
13
+ Rake::TestTask.new(:test) do |t|
14
+ t.libs << "test"
15
+ t.libs << "lib"
16
+
17
+ file_name = ARGV[1]
18
+
19
+ t.test_files = if file_name
20
+ [file_name]
21
+ else
22
+ FileList["test/**/*_test.rb"]
23
+ end
24
+ end
25
+
26
+ task default: [:test, :standard]
@@ -2,17 +2,11 @@
2
2
 
3
3
  # This handler accepts webhooks from our integration tests. This webhook gets dispatched
4
4
  # if a banking provider test fails, indicating that the bank might be having an incident
5
-
6
5
  class WebhookTestHandler < Munster::BaseHandler
7
6
  def valid?(request) = true
8
7
 
9
8
  def process(webhook)
10
- return unless webhook.received?
11
- webhook.update!(status: "processing")
12
- webhook.update!(status: "processed")
13
- rescue
14
- webhook.update!(status: "error")
15
- raise
9
+ Rails.logger.info { webhook.request.params.fetch(:payment_id) }
16
10
  end
17
11
 
18
12
  def expose_errors_to_sender? = true
@@ -3,5 +3,7 @@
3
3
  require_relative "../../app/webhooks/webhook_test_handler"
4
4
 
5
5
  Munster.configure do |config|
6
- config.active_handlers = [WebhookTestHandler]
6
+ config.active_handlers = {
7
+ "test-handler" => "WebhookTestHandler"
8
+ }
7
9
  end
@@ -0,0 +1,36 @@
1
+ # This is an example handler for Customer.io reporting webhooks. You
2
+ # can find more documentation here https://customer.io/docs/api/webhooks/#operation/reportingWebhook
3
+ class Webhooks::CustomerIoHandler < Munster::BaseHandler
4
+ def process(webhook)
5
+ json = JSON.parse(webhook.body, symbolize_names: true)
6
+ case json[:metric]
7
+ when "subscribed"
8
+ # ...
9
+ when "unsubscribed"
10
+ # ...
11
+ when "cio_subscription_preferences_changed"
12
+ # ...
13
+ end
14
+ end
15
+
16
+ def extract_event_id_from_request(action_dispatch_request)
17
+ action_dispatch_request.params.fetch(:event_id)
18
+ end
19
+
20
+ # Verify that request is actually comming from customer.io here
21
+ # @see https://customer.io/docs/api/webhooks/#section/Securely-Verifying-Requests
22
+ #
23
+ # - Should have "X-CIO-Signature", "X-CIO-Timestamp" headers.
24
+ # - Combine the version number, timestamp and body delimited by colons to form a string in the form v0:<timestamp>:<body>
25
+ # - Using HMAC-SHA256, hash the string using your webhook signing secret as the hash key.
26
+ # - Compare this value to the value of the X-CIO-Signature header sent with the request to confirm
27
+ def valid?(action_dispatch_request)
28
+ signing_key = Rails.application.secrets.customer_io_webhook_signing_key
29
+ xcio_signature = action_dispatch_request.headers["HTTP_X_CIO_SIGNATURE"]
30
+ xcio_timestamp = action_dispatch_request.headers["HTTP_X_CIO_TIMESTAMP"]
31
+ request_body = action_dispatch_request.body.read
32
+ string_to_sign = "v0:#{xcio_timestamp}:#{request_body}"
33
+ hmac = OpenSSL::HMAC.hexdigest("SHA256", signing_key, string_to_sign)
34
+ Rack::Utils.secure_compare(hmac, xcio_signature)
35
+ end
36
+ end
@@ -0,0 +1,29 @@
1
+ # This is for Revolut V1 API for webhooks - https://developer.revolut.com/docs/business/webhooks-v-1-deprecated
2
+ class RevolutBusinessV1Handler < Munster::BaseHandler
3
+ def valid?(_)
4
+ # V1 of Revolut webhooks does not support signatures
5
+ true
6
+ end
7
+
8
+ def self.process(webhook)
9
+ parsed_payload = JSON.parse(webhook.body)
10
+ topic = parsed_payload.fetch("Topic")
11
+ case topic
12
+ when "tokens" # Account access revocation payload
13
+ # ...
14
+ when "draftpayments/transfers" # Draft payment transfer notification payload
15
+ # ...
16
+ else
17
+ # ...
18
+ end
19
+ end
20
+
21
+ def self.extract_event_id_from_request(action_dispatch_request)
22
+ # Since b-tree indices generally divide from the start of the string, place the highest
23
+ # entropy component at the start (the EventId)
24
+ key_components = %w[EventId Topic Version]
25
+ key_components.map do |key|
26
+ action_dispatch_request.params.fetch(key)
27
+ end.join("-")
28
+ end
29
+ end
@@ -0,0 +1,42 @@
1
+ # This is for Revolut V2 API for webhooks - https://developer.revolut.com/docs/business/webhooks-v-2
2
+ class RevolutBusinessV2Handler < Munster::BaseHandler
3
+ def valid?(request)
4
+ # 1 - Validate the timestamp of the request. Prevent replay attacks.
5
+ # "To validate the event, make sure that the Revolut-Request-Timestamp date-time is within a 5-minute time tolerance of the current universal time (UTC)".
6
+ # Their examples list `timestamp = '1683650202360'` as a sample value, so their timestamp is in millis - not in seconds
7
+ timestamp_str_from_headers = request.headers["HTTP_REVOLUT_REQUEST_TIMESTAMP"]
8
+ delta_t_seconds = (timestamp_str_from_headers / 1000) - Time.now.to_i
9
+ return false unless delta_t_seconds.abs < (5 * 60)
10
+
11
+ # 2 - Validate the signature
12
+ # https://developer.revolut.com/docs/guides/manage-accounts/tutorials/work-with-webhooks/verify-the-payload-signature
13
+ string_to_sign = [
14
+ "v1",
15
+ timestamp_str_from_headers,
16
+ request.body.read
17
+ ].join(".")
18
+ computed_signature = "v1=" + OpenSSL::HMAC.hexdigest("SHA256", Rails.application.secrets.revolut_business_webhook_signing_key, string_to_sign)
19
+ # Note: "This means that in the period when multiple signing secrets remain valid, multiple signatures are sent."
20
+ # https://developer.revolut.com/docs/guides/manage-accounts/tutorials/work-with-webhooks/manage-webhooks#rotate-a-webhook-signing-secret
21
+ # https://developer.revolut.com/docs/guides/manage-accounts/tutorials/work-with-webhooks/about-webhooks#security
22
+ # An HTTP header may contain multiple values if it gets sent multiple times. But it does mean we need to test for multiple provided
23
+ # signatures in case of rotation.
24
+ provided_signatures = request.headers["HTTP_REVOLUT_SIGNATURE"].split(",")
25
+ # Use #select instead of `find` to compare all signatures even if only one matches - this to avoid timing leaks.
26
+ # Small effort but might be useful.
27
+ matches = provided_signatures.select do |provided_signature|
28
+ ActiveSupport::SecurityUtils.secure_compare(provided_signature, computed_signature)
29
+ end
30
+ matches.any?
31
+ end
32
+
33
+ def self.process(webhook)
34
+ Rails.logger.info { "Processing Revolut webhook #{webhook.body.inspect}" }
35
+ end
36
+
37
+ def self.extract_event_id_from_request(action_dispatch_request)
38
+ # The event ID is only available when you retrieve the failed webhooks, which is sad.
39
+ # We can divinate a synthetic ID though by taking a hash of the entire payload though.
40
+ Digest::SHA256.hexdigest(action_dispatch_request.body.read)
41
+ end
42
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This handler is an example for Starling Payments API,
4
+ # you can find the documentation here https://developer.starlingbank.com/payments/docs#account-and-address-structure-1
5
+ class StarlingPaymentsHandler < Munster::BaseHandler
6
+ # This method will be used to process webhook by async worker.
7
+ def process(received_webhook)
8
+ Rails.logger.info { received_webhook.body }
9
+ end
10
+
11
+ # Starling supplies signatures in the form SHA512(secret + request_body)
12
+ def valid?(action_dispatch_request)
13
+ supplied_signature = action_dispatch_request.headers.fetch("X-Hook-Signature")
14
+ supplied_digest_bytes = Base64.strict_decode64(supplied_signature)
15
+ sha512 = Digest::SHA2.new(512)
16
+ signing_secret = Rails.credentials.starling_payments_webhook_signing_secret
17
+ computed_digest_bytes = sha512.digest(signing_secret.b + action_dispatch_request.body.b)
18
+ ActiveSupport::SecurityUtils.secure_compare(computed_digest_bytes, supplied_digest_bytes)
19
+ end
20
+
21
+ # Some Starling webhooks do not provide a notification UID, but for those which do we can deduplicate
22
+ def extract_event_id_from_request(action_dispatch_request)
23
+ action_dispatch_request.params.fetch("notificationUid", SecureRandom.uuid)
24
+ end
25
+ end
@@ -4,40 +4,74 @@ require_relative "jobs/processing_job"
4
4
 
5
5
  module Munster
6
6
  class BaseHandler
7
- # Gets called from the background job
8
- def self.process(...)
9
- new.process(...)
7
+ # `handle` accepts the ActionDispatch HTTP request and saves the webhook for later processing. It then
8
+ # enqueues an ActiveJob which will perform the processing using `process`.
9
+ #
10
+ # @param action_dispatch_request[ActionDispatch::Request] the request from the controller
11
+ # @return [void]
12
+ def handle(action_dispatch_request)
13
+ handler_module_name = is_a?(Munster::BaseHandler) ? self.class.name : to_s
14
+ handler_event_id = extract_event_id_from_request(action_dispatch_request)
15
+
16
+ webhook = Munster::ReceivedWebhook.new(request: action_dispatch_request, handler_event_id: handler_event_id, handler_module_name: handler_module_name)
17
+ webhook.save!
18
+
19
+ enqueue(webhook)
20
+ rescue ActiveRecord::RecordNotUnique # Webhook deduplicated
21
+ Rails.logger.info { "#{inspect} Webhook #{handler_event_id} is a duplicate delivery and will not be stored." }
10
22
  end
11
23
 
12
- # Reimplement this method, it's being used in WebhooksController to store incoming webhook.
13
- # Also que for processing in the end.
24
+ # Enqueues the processing job to process webhook asynchronously. The job class could be configured.
25
+ #
26
+ # @param webhook [Munster::ReceivedWebhook]
14
27
  # @return [void]
15
- def handle(action_dispatch_request)
16
- binary_body_str = action_dispatch_request.body.read.force_encoding(Encoding::BINARY)
17
- attrs = {
18
- body: binary_body_str,
19
- handler_module_name: self.class.name,
20
- handler_event_id: extract_event_id_from_request(action_dispatch_request)
21
- }
22
- webhook = Munster::ReceivedWebhook.create!(**attrs)
23
-
24
- Munster.configuration.processing_job_class.perform_later(webhook)
25
- rescue ActiveRecord::RecordNotUnique # Deduplicated
26
- nil
28
+ def enqueue(webhook)
29
+ # The configured job class can be a class name or a module, to support lazy loading
30
+ job_class_or_module_name = Munster.configuration.processing_job_class
31
+ job_class = if job_class_or_module_name.respond_to?(:perform_later)
32
+ job_class_or_module_name
33
+ else
34
+ job_class_or_module_name.constantize
35
+ end
36
+
37
+ job_class.perform_later(webhook)
27
38
  end
28
39
 
29
- # This method will be used to process webhook by async worker.
40
+ # This is the heart of your webhook processing. Override this method and define your processing inside of it.
41
+ # The `received_webhook` will provide access to the `ReceivedWebhook` model, which contains the received
42
+ # body of the webhook request, but also the full (as-full-as-possible) clone of the original ActionDispatch::Request
43
+ # that you can use.
44
+ #
45
+ # @param received_webhook[Munster::ReceivedWebhook]
46
+ # @return [void]
30
47
  def process(received_webhook)
31
48
  end
32
49
 
33
- # This method verifies that request actually comes from provider:
34
- # signature validation, HTTP authentication, IP whitelisting and the like
50
+ # This method verifies that request is not malformed and actually comes from the webhook sender:
51
+ # signature validation, HTTP authentication, IP whitelisting and the like. There is a difference depending
52
+ # on whether you validate sync (in the receiving controller) or async (in the processing job):
53
+ # Validation is async - it takes place in the background job that gets enqueued to process the webhook.
54
+ # The `action_dispatch_request` will be reconstructed from the `ReceivedWebhook` data. Background validation
55
+ # is used because the most common misconfiguration that may occur is usually forgetting or misidentifying the
56
+ # signature for signed webhooks. If such a misconfiguration has taken place, the background validation
57
+ # (instead of rejecting the webhook at input) permits you to still process the webhook once the secrets
58
+ # have been configured correctly.
59
+ #
60
+ # If this method returns `false`, the webhook will be marked as `failed_validation` in the database. If this
61
+ # method returns `true`, the `process` method of the handler is going to be called.
62
+ #
63
+ # @see Munster::ReceivedWebhook#request
64
+ # @param action_dispatch_request[ActionDispatch::Request] the reconstructed request from the controller
65
+ # @return [Boolean]
35
66
  def valid?(action_dispatch_request)
36
67
  true
37
68
  end
38
69
 
39
- # Default implementation just generates UUID, but if the webhook sender sends us
40
- # an event ID we use it for deduplication.
70
+ # Default implementation just generates a random UUID, but if the webhook sender sends us
71
+ # an event ID we use it for deduplication. A duplicate webhook is not going to be
72
+ # stored in the database if it is already present there.
73
+ #
74
+ # @return [String]
41
75
  def extract_event_id_from_request(action_dispatch_request)
42
76
  SecureRandom.uuid
43
77
  end
@@ -47,6 +81,8 @@ module Munster
47
81
  # data and do not disable your endpoint forcibly. We allow this to be configured
48
82
  # on a per-handler basis - a better webhooks sender will be able to make out
49
83
  # some sense of the errors.
84
+ #
85
+ # @return [Boolean]
50
86
  def expose_errors_to_sender?
51
87
  true
52
88
  end
@@ -55,6 +91,8 @@ module Munster
55
91
  # to deactivate a particular handler via feature flags for example, or use other
56
92
  # logic to determine whether the handler may be used to create new received webhooks
57
93
  # in the system. This is primarily needed for load shedding.
94
+ #
95
+ # @return [Boolean]
58
96
  def active?
59
97
  true
60
98
  end
@@ -2,55 +2,54 @@
2
2
 
3
3
  module Munster
4
4
  class ReceiveWebhooksController < ActionController::API
5
- class HandlerRefused < StandardError
5
+ class HandlerInactive < StandardError
6
6
  end
7
7
 
8
- class HandlerInactive < StandardError
8
+ class UnknownHandler < StandardError
9
9
  end
10
10
 
11
11
  def create
12
- handler = lookup_handler(params[:service_id]).new
13
-
12
+ Rails.error.set_context(**Munster.configuration.error_context)
13
+ handler = lookup_handler(service_id)
14
14
  raise HandlerInactive unless handler.active?
15
- raise HandlerRefused unless handler.valid?(request)
16
-
17
15
  handler.handle(request)
18
- head :ok
19
- rescue KeyError # handler was not found, so we return generic 404 error.
20
- render_error("Required parameters were not present in the request", :not_found)
16
+ render(json: {ok: true, error: nil})
17
+ rescue UnknownHandler => e
18
+ Rails.error.report(e, handled: true, severity: :error)
19
+ render_error_with_status("No handler found for #{service_id.inspect}", status: :not_found)
20
+ rescue HandlerInactive => e
21
+ Rails.error.report(e, handled: true, severity: :error)
22
+ render_error_with_status("Webhook handler #{service_id.inspect} is inactive", status: :service_unavailable)
21
23
  rescue => e
22
- Rails.error.set_context(**Munster.configuration.error_context)
23
- # Rails 7.1 only requires `error` attribute for .report method, but Rails 7.0 requires `handled:` attribute additionally.
24
- # We're setting `handled:` and `severity:` attributes to maintain compatibility with all versions of > rails 7.
24
+ raise e unless handler
25
+ raise e if handler.expose_errors_to_sender?
25
26
  Rails.error.report(e, handled: true, severity: :error)
26
-
27
- if handler&.expose_errors_to_sender?
28
- error_for_sender_from_exception(e)
29
- else
30
- head :ok
31
- end
27
+ render_error_with_status("Internal error (#{e})")
32
28
  end
33
29
 
34
- def error_for_sender_from_exception(e)
35
- case e
36
- when HandlerRefused
37
- render_error("Webhook handler did not validate the request (signature or authentication may be invalid)", :forbidden)
38
- when HandlerInactive
39
- render_error("Webhook handler is inactive", :service_unavailable)
40
- when JSON::ParserError
41
- render_error("Request body is not a valid JSON", :bad_request)
42
- else
43
- render_error("Internal error", :internal_server_error)
44
- end
30
+ def service_id
31
+ params.require(:service_id)
45
32
  end
46
33
 
47
- def render_error(message_str, status_sym)
48
- json = {error: message_str}.to_json
49
- render(json: json, status: status_sym)
34
+ def render_error_with_status(message_str, status: :ok)
35
+ json = {ok: false, error: message_str}.to_json
36
+ render(json: json, status: status)
50
37
  end
51
38
 
52
39
  def lookup_handler(service_id_str)
53
- Munster.configuration.active_handlers.with_indifferent_access.fetch(service_id_str)
40
+ active_handlers = Munster.configuration.active_handlers.with_indifferent_access
41
+ # The config can specify a mapping of:
42
+ # {"service-1" => MyHandler }
43
+ # or
44
+ # {"service-2" => "MyOtherHandler"}
45
+ # We need to support both, because `MyHandler` is not loaded yet when Rails initializers run.
46
+ # Zeitwerk takes over after the initializers. So we can't really use a module in the init cycle just yet.
47
+ # We can, however, use the module name - and resolve it lazily, later.
48
+ handler_class_or_class_name = active_handlers.fetch(service_id_str)
49
+ handler_class = handler_class_or_class_name.respond_to?(:constantize) ? handler_class_or_class_name.constantize : handler_class_or_class_name
50
+ handler_class.new
51
+ rescue KeyError
52
+ raise UnknownHandler
54
53
  end
55
54
  end
56
55
  end
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative "../munster"
4
3
  require_relative "controllers/receive_webhooks_controller"
5
4
  require_relative "jobs/processing_job"
6
5
  require_relative "models/received_webhook"
@@ -10,7 +9,6 @@ module Munster
10
9
  class Engine < ::Rails::Engine
11
10
  isolate_namespace Munster
12
11
 
13
- autoload :Munster, "munster"
14
12
  autoload :ReceiveWebhooksController, "munster/controllers/receive_webhooks_controller"
15
13
  autoload :ProcessingJob, "munster/jobs/processing_job"
16
14
  autoload :BaseHandler, "munster/base_handler"
@@ -18,5 +16,9 @@ module Munster
18
16
  generators do
19
17
  require_relative "install_generator"
20
18
  end
19
+
20
+ routes do
21
+ post "/:service_id" => "received_webhooks#create"
22
+ end
21
23
  end
22
24
  end
@@ -15,6 +15,7 @@ module Munster
15
15
 
16
16
  def create_migration_file
17
17
  migration_template "create_munster_tables.rb.erb", File.join(db_migrate_path, "create_munster_tables.rb")
18
+ migration_template "add_headers_to_munster_webhooks.rb.erb", File.join(db_migrate_path, "add_headers_to_munster_webhooks.rb")
18
19
  end
19
20
 
20
21
  def copy_files
@@ -1,14 +1,31 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "active_job" if defined?(Rails)
3
+ require "active_job/railtie"
4
4
 
5
5
  module Munster
6
6
  class ProcessingJob < ActiveJob::Base
7
+ class WebhookPayloadInvalid < StandardError
8
+ end
9
+
7
10
  def perform(webhook)
8
- # TODO: there should be some sort of locking or concurrency control here, but it's outside of
9
- # Munsters scope of responsibility. Developer implementing this should decide how this should be handled.
10
- webhook.handler.process(webhook)
11
- # TODO: remove process attribute
11
+ Rails.error.set_context(munster_handler_module_name: webhook.handler_module_name, **Munster.configuration.error_context)
12
+
13
+ webhook.with_lock do
14
+ return unless webhook.received?
15
+ webhook.processing!
16
+ end
17
+
18
+ if webhook.handler.valid?(webhook.request)
19
+ webhook.handler.process(webhook)
20
+ webhook.processed! if webhook.processing?
21
+ else
22
+ e = WebhookPayloadInvalid.new("#{webhook.class} #{webhook.id} did not pass validation and was skipped")
23
+ Rails.error.report(e, handled: true, severity: :error)
24
+ webhook.failed_validation!
25
+ end
26
+ rescue => e
27
+ webhook.error!
28
+ raise e
12
29
  end
13
30
  end
14
31
  end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require 'state_machine_enum'
3
+ require "state_machine_enum"
4
4
 
5
5
  module Munster
6
6
  class ReceivedWebhook < ActiveRecord::Base
@@ -11,13 +11,89 @@ module Munster
11
11
 
12
12
  state_machine_enum :status do |s|
13
13
  s.permit_transition(:received, :processing)
14
+ s.permit_transition(:processing, :failed_validation)
14
15
  s.permit_transition(:processing, :skipped)
15
16
  s.permit_transition(:processing, :processed)
16
17
  s.permit_transition(:processing, :error)
18
+ s.permit_transition(:error, :received)
19
+
20
+ s.after_committed_transition_to(:received) do |webhook|
21
+ webhook.handler.enqueue(webhook)
22
+ end
23
+ end
24
+
25
+ # Store the pertinent data from an ActionDispatch::Request into the webhook.
26
+ # @param [ActionDispatch::Request]
27
+ def request=(action_dispatch_request)
28
+ # Filter out all Rack-specific headers such as "rack.input" and the like. We are
29
+ # only interested in the actual HTTP headers presented by the webserver. Mostly...
30
+ headers = action_dispatch_request.env.filter_map do |(header_name, header_value)|
31
+ if header_name.is_a?(String) && header_name.upcase == header_name && header_value.is_a?(String)
32
+ [header_name, header_value]
33
+ end
34
+ end.to_h
35
+
36
+ # ...except the path parameters - they do not get parsed from the headers, but instead get set by Journey - the Rails
37
+ # router - when the ActionDispatch::Request object gets instantiated. They need to be preserved separately in case the Munster
38
+ # controller gets mounted under a parametrized path - and the path component actually is a parameter that the webhook
39
+ # handler either needs for validation or for processing
40
+ headers["action_dispatch.request.path_parameters"] = action_dispatch_request.env.fetch("action_dispatch.request.path_parameters")
41
+
42
+ # ...and the raw request body - because we already save it separately
43
+ headers.delete("RAW_POST_DATA")
44
+
45
+ # Verify the request body is not too large
46
+ request_body_io = action_dispatch_request.env.fetch("rack.input")
47
+ if request_body_io.size > Munster.configuration.request_body_size_limit
48
+ raise "Cannot accept the webhook as the request body is larger than #{limit} bytes"
49
+ end
50
+
51
+ write_attribute("body", request_body_io.read.force_encoding(Encoding::BINARY))
52
+ write_attribute("request_headers", headers)
53
+ ensure
54
+ request_body_io.rewind
55
+ end
56
+
57
+ # A Munster handler is, in a way, a tiny Rails controller which runs in a background job. To allow this,
58
+ # we need to provide access not only to the webhook payload (the HTTP request body, usually), but also
59
+ # to the rest of the HTTP request - such as headers and route params. For example, imagine you use
60
+ # a system where your multiple tenants (users) may receive webhooks from the same sender. However, you
61
+ # need to dispatch those webhooks to those particular tenants of your application. Instead of mounting
62
+ # Munster as an engine under a common route, you mount it like so:
63
+ #
64
+ # post "/incoming-webhooks/:user_id/:service_id" => "munster/receive_webhooks#create"
65
+ #
66
+ # This way, the tenant ID (the `user_id`) parameter is not going to be provided to you inside the webhook
67
+ # payload, as the sender is not sending it to you at all. However, you do have that parameter in your
68
+ # route. When processing the webhook, it is important for you to know which tenant has received the
69
+ # webhook - so that you can manipulate their data, and not the data belonging to another tenant. With
70
+ # validation, it is important too - in such a multitenant setup every user is likely to have their own,
71
+ # specific signing secret that they have set up. To find that secret and compare the signature, you
72
+ # need access to that `user_id` parameter.
73
+ #
74
+ # To allow access to these, Munster allows the ActionDispatch::Request object to be persisted. The
75
+ # persistence is not 1:1 - the Request is a fairly complex object, with lots of things injected into it
76
+ # by the Rails stack. Not all of those injected properties (Rack headers) are marshalable, some of them
77
+ # depend on the Rails application configuration, etc. However, we do retain the most important things
78
+ # for webhooks to be correctly handled.
79
+ #
80
+ # * The HTTP request body
81
+ # * The headers set by the webserver and the downstream proxies
82
+ # * The request body and query string params, depending on the MIME type
83
+ # * The route params. These are set by Journey (the Rails router) and cannot be reconstructed from a "bare" request
84
+ #
85
+ # While this reconstruction is best-effort it might not be lossless. For example, there might be no access
86
+ # to Rack hijack, streaming APIs, the cookie jar or other more high-level Rails request access features.
87
+ # You will, however, have the basics in place - such as the params, the request body, the path params
88
+ # (as were decoded by your routes) etc. But it should be sufficient to do the basic tasks to process a webhook.
89
+ #
90
+ # @return [ActionDispatch::Request]
91
+ def request
92
+ ActionDispatch::Request.new(request_headers.merge!("rack.input" => StringIO.new(body.to_s.b)))
17
93
  end
18
94
 
19
95
  def handler
20
- handler_module_name.constantize
96
+ handler_module_name.constantize.new
21
97
  end
22
98
  end
23
99
  end
@@ -0,0 +1,5 @@
1
+ class AddHeadersToMunsterWebhooks < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ add_column :received_webhooks, :request_headers, :json, null: true
4
+ end
5
+ end
@@ -6,7 +6,7 @@ class CreateMunsterTables < ActiveRecord::Migration<%= migration_version %>
6
6
  t.string :handler_module_name, null: false
7
7
  t.string :status, default: "received", null: false
8
8
 
9
- # We don't assume, that we can always parse received body as JSON. Body could be invalid or partly missing,
9
+ # We don't assume that we can always parse the received body as JSON. Body could be invalid or partly missing,
10
10
  # we can argue how we can handle that for different integrations, but we still should be able to save this data
11
11
  # if it's required. Hence, we don't use :jsonb, but :binary type column here.
12
12
  t.binary :body, null: false
@@ -1,10 +1,15 @@
1
1
  Munster.configure do |config|
2
2
  # Active Handlers are defined as hash with key as a service_id and handler class that would handle webhook request.
3
+ # A Handler must respond to `.new` and return an object roughly matching `Munster::BaseHandler` in terms of interface.
4
+ # Use module names (strings) here to allow the handler modules to be lazy-loaded by Rails.
5
+ #
3
6
  # Example:
4
- # {:test => TestHandler, :inactive => InactiveHandler}
7
+ # {:test => "TestHandler", :inactive => "InactiveHandler"}
5
8
  config.active_handlers = {}
6
9
 
7
- # It's possible to overwrite default processing job to enahance it. As example if you want to add proper locking or retry mechanism.
10
+ # It's possible to overwrite default processing job to enahance it. As example if you want to add custom
11
+ # locking or retry mechanism. You want to inherit that job from Munster::ProcessingJob because the background
12
+ # job also manages the webhook state.
8
13
  #
9
14
  # Example:
10
15
  #
@@ -15,9 +20,9 @@ Munster.configure do |config|
15
20
  # end
16
21
  # end
17
22
  #
18
- # This is how you can change processing job:
23
+ # In the config a string with your job' class name can be used so that the job can be lazy-loaded by Rails:
19
24
  #
20
- # config.processing_job_class = WebhookProcessingJob
25
+ # config.processing_job_class = "WebhookProcessingJob"
21
26
 
22
27
  # We're using a common interface for error reporting provided by Rails, e.g Rails.error.report. In some cases
23
28
  # you want to enhance those errors with additional context. As example to provide a namespace:
@@ -25,4 +30,11 @@ Munster.configure do |config|
25
30
  # { appsignal: { namespace: "webhooks" } }
26
31
  #
27
32
  # config.error_context = { appsignal: { namespace: "webhooks" } }
33
+
34
+ # Incoming webhooks will be written into your DB without any prior validation. By default, Munster limits the
35
+ # request body size for webhooks to 512 KiB, so that it would not be too easy for an attacker to fill your
36
+ # database with junk. However, if you are receiving very large webhook payloads you might need to increase
37
+ # that limit (or make it even smaller for extra security)
38
+ #
39
+ # config.request_body_size_limit = 2.megabytes
28
40
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Munster
4
- VERSION = "0.3.1"
4
+ VERSION = "0.4.1"
5
5
  end
data/lib/munster.rb CHANGED
@@ -18,7 +18,8 @@ end
18
18
  class Munster::Configuration
19
19
  include ActiveSupport::Configurable
20
20
 
21
- config_accessor(:processing_job_class) { Munster::ProcessingJob }
22
- config_accessor(:active_handlers) { [] }
23
- config_accessor(:error_context) { {} }
21
+ config_accessor(:processing_job_class, default: Munster::ProcessingJob)
22
+ config_accessor(:active_handlers, default: {})
23
+ config_accessor(:error_context, default: {})
24
+ config_accessor(:request_body_size_limit, default: 512.kilobytes)
24
25
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: munster
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.1
4
+ version: 0.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Stanislav Katkov
8
8
  autorequire:
9
- bindir: exe
9
+ bindir: bin
10
10
  cert_chain: []
11
- date: 2024-06-07 00:00:00.000000000 Z
11
+ date: 2024-07-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: rails
@@ -94,7 +94,7 @@ dependencies:
94
94
  - - "~>"
95
95
  - !ruby/object:Gem::Version
96
96
  version: '5.0'
97
- description: Webhooks framework for Rails applications
97
+ description: Webhooks processing engine for Rails applications
98
98
  email:
99
99
  - skatkov@cheddar.me
100
100
  executables: []
@@ -106,7 +106,6 @@ files:
106
106
  - ".standard.yml"
107
107
  - CHANGELOG.md
108
108
  - LICENSE
109
- - LICENSE.txt
110
109
  - README.md
111
110
  - Rakefile
112
111
  - config/routes.rb
@@ -171,6 +170,10 @@ files:
171
170
  - example/tmp/.keep
172
171
  - example/tmp/pids/.keep
173
172
  - example/vendor/.keep
173
+ - handler-examples/customer_io_handler.rb
174
+ - handler-examples/revolut_business_v1_handler.rb
175
+ - handler-examples/revolut_business_v2_handler.rb
176
+ - handler-examples/starling_payments_handler.rb
174
177
  - lib/munster.rb
175
178
  - lib/munster/base_handler.rb
176
179
  - lib/munster/controllers/receive_webhooks_controller.rb
@@ -178,17 +181,18 @@ files:
178
181
  - lib/munster/install_generator.rb
179
182
  - lib/munster/jobs/processing_job.rb
180
183
  - lib/munster/models/received_webhook.rb
184
+ - lib/munster/templates/add_headers_to_munster_webhooks.rb.erb
181
185
  - lib/munster/templates/create_munster_tables.rb.erb
182
186
  - lib/munster/templates/munster.rb
183
187
  - lib/munster/version.rb
184
188
  - lib/tasks/munster_tasks.rake
185
- - sig/munster.rbs
186
189
  homepage: https://www.cheddar.me/
187
190
  licenses:
188
191
  - MIT
189
192
  metadata:
190
193
  homepage_uri: https://www.cheddar.me/
191
194
  source_code_uri: https://github.com/cheddar-me/munster
195
+ changelog_uri: https://github.com/cheddar-me/munster/blob/main/CHANGELOG.md
192
196
  post_install_message:
193
197
  rdoc_options: []
194
198
  require_paths:
@@ -204,8 +208,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
204
208
  - !ruby/object:Gem::Version
205
209
  version: '0'
206
210
  requirements: []
207
- rubygems_version: 3.5.3
211
+ rubygems_version: 3.5.9
208
212
  signing_key:
209
213
  specification_version: 4
210
- summary: Webhooks framework for Rails applications
214
+ summary: Webhooks processing engine for Rails applications
211
215
  test_files: []
data/LICENSE.txt DELETED
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2024 Stanislav Katkov
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
data/sig/munster.rbs DELETED
@@ -1,4 +0,0 @@
1
- module Munster
2
- VERSION: String
3
- # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
- end