Skip to content

Commit

Permalink
Add support for verifying webhook signatures (#413)
Browse files Browse the repository at this point in the history
This PR adds support for verifying the webhook signature of inbound webhook notifications.
  • Loading branch information
mrashed-dev committed Mar 30, 2023
1 parent 860d8b6 commit 27c3e37
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

### Unreleased
* Add support for verifying webhook signatures

### 5.16.0 / 2022-03-14
* Add missing `provider_id` attribute to `Label`
* Add `organizer_email` and `organizer_name` to `Event`
Expand Down
11 changes: 11 additions & 0 deletions lib/nylas/webhook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ module Nylas
# Represents a webhook attached to your application.
# @see https://docs.nylas.com/reference#webhooks
class Webhook
require "openssl"
include Model
self.creatable = true
self.listable = true
Expand Down Expand Up @@ -91,6 +92,16 @@ def self.resources_path(api:)
"/a/#{api.app_id}/webhooks"
end

# Verify incoming webhook signature came from Nylas
# @param nylas_signature [str] The signature to verify
# @param raw_body [str] The raw body from the payload
# @param client_secret [str] Client secret of the app receiving the webhook
# @return [Boolean] True if the webhook signature was verified from Nylas
def self.verify_webhook_signature(nylas_signature, raw_body, client_secret)
digest = OpenSSL::HMAC.hexdigest("SHA256", client_secret, raw_body)
digest == nylas_signature
end

private

def update_payload
Expand Down
22 changes: 22 additions & 0 deletions spec/nylas/webhook_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -201,4 +201,26 @@
)
end
end

describe "verify_webhook_signature" do
it "returns true if the webhook signature is valid" do
is_verified = described_class.verify_webhook_signature(
"ddc02f921a4835e310f249dc09770c3fea2cb6fe949adc1887d7adc04a581e1c",
"test123",
"myClientSecret"
)

expect(is_verified).to be(true)
end

it "returns false if the webhook signature is invalid" do
is_verified = described_class.verify_webhook_signature(
"ddc02f921a4835e310f249dc09770c3fea2cb6fe949adc1887d7adc04a581e1c",
"test1234",
"myClientSecret"
)

expect(is_verified).to be(false)
end
end
end

0 comments on commit 27c3e37

Please sign in to comment.