Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Adds Spree::Webhooks::EventSignature to compute a unique signature

Stefan Vermaas5b54a36e9eed
diff --git a/api/app/models/spree/webhooks/event_signature.rb b/api/app/models/spree/webhooks/event_signature.rb
new file mode 100644
index 0000000000..69d478842d
--- /dev/null
+++ b/api/app/models/spree/webhooks/event_signature.rb
@@ -0,0 +1,33 @@
+require 'base64'
+require 'openssl'
+
+module Spree
+ module Webhooks
+ class EventSignature
+ def initialize(event, payload)
+ @event = event
+ @payload = payload
+ end
+
+ # Generates a base64-encoded HMAC SHA256 signature for the payload of the event.
+ #
+ # By using the stringified payload, the signature is made tamper-proof as any
+ # alterations of the data during transit will lead to an incorrect signature
+ # comparison by the client.
+ #
+ # @return [String] The computed signature
+ def computed_signature
+ @computed_signature ||=
+ Base64.strict_encode64(
+ OpenSSL::HMAC.digest('sha256', @event.subscriber.secret_key, payload)
+ )
+ end
+
+ private
+
+ def payload
+ @payload.is_a?(String) ? @payload : @payload.to_json
+ end
+ end
+ end
+end
diff --git a/api/spec/models/spree/webhooks/event_signature_spec.rb b/api/spec/models/spree/webhooks/event_signature_spec.rb
new file mode 100644
index 0000000000..7b41f7d93f
--- /dev/null
+++ b/api/spec/models/spree/webhooks/event_signature_spec.rb
@@ -0,0 +1,25 @@
+require 'spec_helper'
+
+describe Spree::Webhooks::EventSignature do
+ subject(:signature) { described_class.new(webhook_event, event_payload) }
+
+ let(:event_payload) { { event_name: 'order.create', data: { id: 123 } } }
+ let(:webhook_event) { create(:webhook_event) }
+
+ describe '#computed_signature' do
+ it 'computes a unique signature per payload' do
+ order_finished_signature =
+ described_class.new(webhook_event, { event_name: 'order.finished', data: { id: 123 } })
+
+ expect(signature.computed_signature).
+ not_to eq(order_finished_signature.computed_signature)
+ end
+
+ it 'computes a stable signature for the same payload' do
+ order_created_signature = described_class.new(webhook_event, event_payload)
+
+ expect(signature.computed_signature).
+ to eq(order_created_signature.computed_signature)
+ end
+ end
+end