From aec1d6fb25d1fc1aa101ee5fbfbe6788c24d9947 Mon Sep 17 00:00:00 2001 From: Benjamin Ragheb Date: Wed, 13 Nov 2024 14:32:25 -0500 Subject: [PATCH] Don't mutate WebhooksHelper parameters The `is_valid_webhook_event_signature` method would raise an exception if the passed in `signature_key` string was frozen, which it arguably always should be! Enabling frozen string literals in the test file causes most of the tests to fail. The underlying problem was a call to `force_encoding` which does not appear to be necessary; changing the string's encoding this way will not change the underlying bytes, and so should not have any effect on digest calculation. Since I could not find anything in the repository history or issues to explain why the encoding step was there, I removed it. --- lib/square/utilities/webhooks_helper.rb | 7 +++---- test/webhooks/test_webhooks_helper.rb | 2 ++ 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/square/utilities/webhooks_helper.rb b/lib/square/utilities/webhooks_helper.rb index ddfb9c7f..4d248041 100644 --- a/lib/square/utilities/webhooks_helper.rb +++ b/lib/square/utilities/webhooks_helper.rb @@ -8,12 +8,11 @@ def self.is_valid_webhook_event_signature(request_body, signature_header, signat raise 'signature_key is null or empty' if signature_key.nil? || signature_key.empty? raise 'notification_url is null or empty' if notification_url.nil? || notification_url.empty? - # Perform UTF-8 encoding to bytes - payload_bytes = "#{notification_url}#{request_body}".force_encoding('utf-8') - signature_key_bytes = signature_key.force_encoding('utf-8') + # Prepare the message as it was signed by the sender + message = "#{notification_url}#{request_body}" # Compute the hash value - hmac = OpenSSL::HMAC.digest('sha256', signature_key_bytes, payload_bytes) + hmac = OpenSSL::HMAC.digest('sha256', signature_key, message) # Compare the computed hash vs the value in the signature header hash_base64 = Base64.strict_encode64(hmac) diff --git a/test/webhooks/test_webhooks_helper.rb b/test/webhooks/test_webhooks_helper.rb index ce38ae26..710dfb07 100644 --- a/test/webhooks/test_webhooks_helper.rb +++ b/test/webhooks/test_webhooks_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require_relative '../../lib/square/utilities/webhooks_helper.rb' require 'minitest/autorun' require 'minitest/hell'