Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/stripe/resources.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1940,6 +1940,7 @@ module Core
autoload :ClaimableSandbox, "stripe/resources/v2/core/claimable_sandbox"
autoload :ConnectionSession, "stripe/resources/v2/core/connection_session"
autoload :Event, "stripe/resources/v2/core/event"
autoload :EventBase, "stripe/resources/v2/core/event_base"
autoload :EventDestination, "stripe/resources/v2/core/event_destination"
autoload :EventNotification, "stripe/resources/v2/core/event_notification"
autoload :EventReason, "stripe/resources/v2/core/event_notification"
Expand Down Expand Up @@ -2085,6 +2086,7 @@ module Tax
module Stripe
# rubocop:disable Metrics/CollectionLiteralLength
RESOURCE_FILES = %w[
stripe/resources/v2/core/event_base
stripe/resources/v2/core/event_notification
stripe/resources/account
stripe/resources/account_link
Expand Down
2 changes: 1 addition & 1 deletion lib/stripe/resources/v2/core/event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module V2
module Core
# Events are generated to keep you informed of activity in your business account. APIs in the /v2 namespace generate [thin events](https://docs.stripe.com/event-destinations#benefits-of-thin-events) which have small, unversioned payloads that include a reference to the ID of the object that has changed. The Events v2 API returns these new thin events. [Retrieve the event object](https://docs.stripe.com/event-destinations#fetch-data) for additional data about the event. Use the related object ID in the event payload to [fetch the API resource](https://docs.stripe.com/event-destinations#retrieve-the-object-associated-with-thin-events) of the object associated with the event. Comparatively, events generated by most API v1 include a versioned snapshot of an API object in their payload.
# You can access events through the [Retrieve Event API](https://docs.stripe.com/api/v2/core/events/retrieve) for 30 days.
class Event < APIResource
class Event < EventBase
OBJECT_NAME = "v2.core.event"
def self.object_name
"v2.core.event"
Expand Down
36 changes: 36 additions & 0 deletions lib/stripe/resources/v2/core/event_base.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

module Stripe
module V2
module Core
class EventBase < APIResource
# internal use: a requestor scoped to this event's own Stripe-Context,
# discarding any Stripe-Account the configured requestor may carry.
# `context`, not account, is what routes a direct-retrieve `Event` (and
# requests made through #fetch_related_object) to the right account --
# mirrors how EventNotification#initialize scopes @client.
private def scoped_requestor
@scoped_requestor ||= begin
scoped_config = @requestor.config.reverse_duplicate_merge(
stripe_account: nil, stripe_context: context
)
APIRequestor.new(scoped_config)
end
end

# Overridden so that every generated `fetch_related_object` (which calls
# this method) routes through #scoped_requestor. Still combines with this
# event's retained @opts so a retained api_key/stripe_version override
# survives, but with @opts's own stripe_account/stripe_context forced to
# the safe values first, since those are exactly what may be stale left
# over from how this Event itself was retrieved.
protected def _request(method:, path:, base_address:, params: {}, opts: {})
req_opts = RequestOptions.extract_opts_from_hash(opts)
safe_opts = @opts.merge(stripe_account: nil, stripe_context: context)
req_opts = RequestOptions.combine_opts(safe_opts, req_opts)
scoped_requestor.execute_request(method, path, base_address, params: params, opts: req_opts)
end
end
end
end
end
63 changes: 61 additions & 2 deletions lib/stripe/webhook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ def self._maybe_extract_from_cloud_provider_envelope(payload)

module Signature
EXPECTED_SCHEME = "v1"
DebugMetadata = Struct.new(:secret, :destination, :payload)
private_constant :DebugMetadata

# Computes a webhook signature given a time (probably the current time),
# a payload, and a signing secret.
Expand Down Expand Up @@ -110,7 +112,7 @@ def self.generate_header(timestamp, signature, scheme: EXPECTED_SCHEME)
def self.get_timestamp_and_signatures(header, scheme)
list_items = header.split(/,\s*/).map { |i| i.split("=", 2) }
timestamp = Integer(list_items.select { |i| i[0] == "t" }[0][1])
signatures = list_items.select { |i| i[0] == scheme }.map { |i| i[1] }
signatures = list_items.select { |i| i[0] == scheme }.map { |i| i[1] }.compact
[Time.at(timestamp), signatures]
end
private_class_method :get_timestamp_and_signatures
Expand Down Expand Up @@ -152,7 +154,7 @@ def self.verify_header(payload, header, secret, tolerance: nil)
expected_sig = compute_signature(timestamp, payload, secret)
unless signatures.any? { |s| Util.secure_compare(expected_sig, s) }
raise SignatureVerificationError.new(
"No signatures found matching the expected signature for payload",
signature_error_message(header, payload, secret),
header, http_body: payload
)
end
Expand All @@ -167,6 +169,63 @@ def self.verify_header(payload, header, secret, tolerance: nil)

true
end

private_class_method def self.signature_error_message(header, payload, secret)
debug_metadata = signature_debug_metadata(header)

# If metadata has an asterisk-masked secret, compare against its length and last four characters
masked_secret = debug_metadata.secret || ""
masked_suffix = masked_secret[-4, 4]
secret_suffix = secret[-4, 4] || secret
if masked_secret&.include?("*") && (secret.length != masked_secret.length || secret_suffix != masked_suffix)
dashboard_url = "https://dashboard.stripe.com/webhooks"
dashboard_url += "/#{CGI.escape(debug_metadata.destination)}" if debug_metadata.destination
return "Webhook signature verification failed. This request may not have originated from Stripe.\n\n" \
"The signing secret you provided is #{secret.length} characters long " \
"and ends in `#{secret_suffix}`. " \
"However, the signing secret for this destination is #{masked_secret.length} characters long " \
"and looks like `#{masked_secret}`. Ensure you're using the signing secret for this " \
"destination, as shown on the Dashboard: #{dashboard_url}\n\n" \
"Learn more: https://docs.stripe.com/webhooks/signature"
end

# If metadata includes the truncated payload hash, compare with the payload passed in
if debug_metadata.payload&.match?(/\A[0-9a-fA-F]{8}\z/)
expected_hash = debug_metadata.payload.downcase
actual_hash = OpenSSL::Digest::SHA256.hexdigest(payload)[-8, 8]
if expected_hash != actual_hash
return "Webhook signature verification failed.\n\n" \
"The request body you passed to this function differs from the request body sent by Stripe " \
"to this webhook destination.\n" \
"The SHA-256 hash of the body should end in `#{expected_hash}`. However, " \
"the SHA-256 hash of the body you provided ends in `#{actual_hash}`.\n\n" \
"Make sure your code does not reformat or otherwise alter the raw HTTP request body " \
"before passing it to this function.\n\n" \
"Learn more: https://docs.stripe.com/webhooks/signature"
end
end

# Fall back to the generic message if no debug metadata available
"No signatures found matching the expected signature for payload"
end

# Extract metadata from the stripe-signature header value to help debug verification failures
private_class_method def self.signature_debug_metadata(header)
# For each metadata key, extract the first value found in the header
metadata = DebugMetadata.new
list_items = header.b.split(/,\s*/).map { |item| item.split("=", 2) }
DebugMetadata.members.each do |key|
value = list_items.assoc(key.to_s)&.[](1)
value&.force_encoding(header.encoding)
metadata[key] = safe_metadata_value?(value) ? value : nil
end
metadata
end

private_class_method def self.safe_metadata_value?(value)
# Ignore overly long, potentially attacker-provided metadata values
value && value.length <= 100 && value.valid_encoding?
end
end
end
end
2 changes: 1 addition & 1 deletion rbi/stripe.rbi
Original file line number Diff line number Diff line change
Expand Up @@ -122194,7 +122194,7 @@ module Stripe
module Core
# Events are generated to keep you informed of activity in your business account. APIs in the /v2 namespace generate [thin events](https://docs.stripe.com/event-destinations#benefits-of-thin-events) which have small, unversioned payloads that include a reference to the ID of the object that has changed. The Events v2 API returns these new thin events. [Retrieve the event object](https://docs.stripe.com/event-destinations#fetch-data) for additional data about the event. Use the related object ID in the event payload to [fetch the API resource](https://docs.stripe.com/event-destinations#retrieve-the-object-associated-with-thin-events) of the object associated with the event. Comparatively, events generated by most API v1 include a versioned snapshot of an API object in their payload.
# You can access events through the [Retrieve Event API](https://docs.stripe.com/api/v2/core/events/retrieve) for 30 days.
class Event < APIResource
class Event < EventBase
class Reason < ::Stripe::StripeObject
class Request < ::Stripe::StripeObject
class Client < ::Stripe::StripeObject
Expand Down
2 changes: 1 addition & 1 deletion rbi/stripe/resources/v2/core/event.rbi
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Stripe
module Core
# Events are generated to keep you informed of activity in your business account. APIs in the /v2 namespace generate [thin events](https://docs.stripe.com/event-destinations#benefits-of-thin-events) which have small, unversioned payloads that include a reference to the ID of the object that has changed. The Events v2 API returns these new thin events. [Retrieve the event object](https://docs.stripe.com/event-destinations#fetch-data) for additional data about the event. Use the related object ID in the event payload to [fetch the API resource](https://docs.stripe.com/event-destinations#retrieve-the-object-associated-with-thin-events) of the object associated with the event. Comparatively, events generated by most API v1 include a versioned snapshot of an API object in their payload.
# You can access events through the [Retrieve Event API](https://docs.stripe.com/api/v2/core/events/retrieve) for 30 days.
class Event < APIResource
class Event < EventBase
class Reason < ::Stripe::StripeObject
class Request < ::Stripe::StripeObject
class Client < ::Stripe::StripeObject
Expand Down
11 changes: 11 additions & 0 deletions rbi/stripe/resources/v2/core/event_base.rbi
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true
# typed: true

module Stripe
module V2
module Core
class EventBase < APIResource
end
end
end
end
3 changes: 2 additions & 1 deletion stripe.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ Gem::Specification.new do |s|
# TODO(helenye): http://go/j/DEVSDK-2769
%r{\Arbi/stripe/stripe_client.rbi\z},
%r{\Arbi/stripe/workload_identity_exchange.rbi\z},
%r{\Arbi/stripe/resources/v2/core/event_notification.rbi\z}
%r{\Arbi/stripe/resources/v2/core/event_notification.rbi\z},
%r{\Arbi/stripe/resources/v2/core/event_base.rbi\z}
)
s.files = `git ls-files`.split("\n").grep(included)
s.bindir = "exe"
Expand Down
88 changes: 88 additions & 0 deletions test/stripe/v2_event_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,94 @@ def parse_signed_event(payload, secret = Test::WebhookHelpers::SECRET)
)
end

should "retain the event context on a directly-retrieved event's related objects" do
client = StripeClient.new(
"test_123",
stripe_account: "acct_platform",
stripe_context: "ctx_platform"
)
stub_request(:get, "#{Stripe::DEFAULT_API_BASE}/v2/core/events/evt_123")
.to_return(body: {
"id" => "evt_123",
"object" => "v2.core.event",
"type" => "v1.product.updated",
"created" => "2022-02-15T00:27:45.330Z",
"context" => "acct_child",
"related_object" => {
"id" => "prod_shared",
"type" => "product",
"url" => "/v1/products/prod_shared",
},
}.to_json)
stub_request(:get, "#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared")
.to_return(body: JSON.generate({ "id" => "prod_shared", "object" => "product" }))
stub_request(:delete, "#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared")
.to_return(body: JSON.generate({ "id" => "prod_shared", "object" => "product", "deleted" => true }))

event = client.v2.core.events.retrieve("evt_123")
product = event.fetch_related_object
product.delete

assert_requested(
:get,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: {
"Authorization" => "Bearer test_123",
"Stripe-Context" => "acct_child",
}
)
assert_requested(
:delete,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: {
"Authorization" => "Bearer test_123",
"Stripe-Context" => "acct_child",
}
)
assert_not_requested(
:get,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: { "Stripe-Account" => "acct_platform" }
)
assert_not_requested(
:delete,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: { "Stripe-Account" => "acct_platform" }
)
end

should "retain a retained api_key override on a directly-retrieved event's related objects" do
client = StripeClient.new("test_123")
stub_request(:get, "#{Stripe::DEFAULT_API_BASE}/v2/core/events/evt_123")
.to_return(body: {
"id" => "evt_123",
"object" => "v2.core.event",
"type" => "v1.product.updated",
"created" => "2022-02-15T00:27:45.330Z",
"related_object" => {
"id" => "prod_shared",
"type" => "product",
"url" => "/v1/products/prod_shared",
},
}.to_json)
stub_request(:get, "#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared")
.to_return(body: JSON.generate({ "id" => "prod_shared", "object" => "product" }))

event = client.v2.core.events.retrieve("evt_123", {}, { api_key: "rk_restricted" })
event.fetch_related_object

assert_requested(
:get,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: { "Authorization" => "Bearer rk_restricted" }
)
assert_not_requested(
:get,
"#{Stripe::DEFAULT_API_BASE}/v1/products/prod_shared",
headers: { "Authorization" => "Bearer test_123" }
)
end

should "correctly retrieve events" do
event_notif = parse_signed_event(@v2_push_payload)
stub_request(:get, "#{Stripe::DEFAULT_API_BASE}/v2/core/events/evt_234")
Expand Down
Loading
Loading