Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new .generate_header method for webhooks #916

Merged
merged 1 commit into from Apr 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions lib/stripe/webhook.rb
Expand Up @@ -39,6 +39,23 @@ def self.compute_signature(timestamp, payload, secret)
timestamped_payload)
end

# Generates a value that would be added to a `Stripe-Signature` for a
# given webhook payload.
#
# Note that this isn't needed to verify webhooks in any way, and is
# mainly here for use in test cases (those that are both within this
# project and without).
def self.generate_header(timestamp, signature, scheme: EXPECTED_SCHEME)
raise ArgumentError, "timestamp should be an instance of Time" \
unless timestamp.is_a?(Time)
raise ArgumentError, "signature should be a string" \
unless signature.is_a?(String)
raise ArgumentError, "scheme should be a string" \
unless scheme.is_a?(String)

"t=#{timestamp.to_i},#{scheme}=#{signature}"
end

# Extracts the timestamp and the signature(s) with the desired scheme
# from the header
def self.get_timestamp_and_signatures(header, scheme)
Expand Down
24 changes: 23 additions & 1 deletion test/stripe/webhook_test.rb
Expand Up @@ -22,7 +22,11 @@ def generate_header(opts = {})
opts[:payload],
opts[:secret]
)
"t=#{opts[:timestamp].to_i},#{opts[:scheme]}=#{opts[:signature]}"
Stripe::Webhook::Signature.generate_header(
opts[:timestamp],
opts[:signature],
scheme: opts[:scheme]
)
end

context ".compute_signature" do
Expand All @@ -38,6 +42,24 @@ def generate_header(opts = {})
end
end

context ".generate_header" do
should "generate a header in valid format" do
timestamp = Time.now
signature = Stripe::Webhook::Signature.compute_signature(
timestamp,
EVENT_PAYLOAD,
SECRET
)
scheme = "v1"
header = Stripe::Webhook::Signature.generate_header(
timestamp,
signature,
scheme: scheme
)
assert_equal("t=#{timestamp.to_i},#{scheme}=#{signature}", header)
end
end

context ".construct_event" do
should "return an Event instance from a valid JSON payload and valid signature header" do
header = generate_header
Expand Down