From 7e43772a6939d2a26ef236dc29d93b36113cf0b3 Mon Sep 17 00:00:00 2001 From: Christopher Orr Date: Mon, 9 Nov 2026 19:33:05 +0100 Subject: [PATCH 1/2] Add error messages to help users debug signature verification failures (#1995) * Add error messages to help users debug signature verification failures. The stripe-signature header may now include additional metadata about the event destination and the event being sent. These can help narrow down the reason why signature verification failed. No changes are made to the verification process; this just updates how error messages are generated, if the metadata is present in the header. * Fix typos. * Guard against malformed key-value pairs in signature header. --- ...rc_webhook-signature-diagnostics.change.md | 6 + lib/stripe/webhook.rb | 63 +++++++++- test/stripe/webhook_test.rb | 117 ++++++++++++++++++ test/test_helper.rb | 6 +- 4 files changed, 189 insertions(+), 3 deletions(-) create mode 100644 .hark/changes/2026-10-12_orrc_webhook-signature-diagnostics.change.md diff --git a/.hark/changes/2026-10-12_orrc_webhook-signature-diagnostics.change.md b/.hark/changes/2026-10-12_orrc_webhook-signature-diagnostics.change.md new file mode 100644 index 000000000..c71498ef1 --- /dev/null +++ b/.hark/changes/2026-10-12_orrc_webhook-signature-diagnostics.change.md @@ -0,0 +1,6 @@ +--- +title: Improve webhook signature verification error messages +semver_level: patch +--- + +- When diagnostic metadata is present in the `Stripe-Signature` header, errors help identify an incorrect signing secret or altered request body. diff --git a/lib/stripe/webhook.rb b/lib/stripe/webhook.rb index f132e049a..b2ef977e2 100644 --- a/lib/stripe/webhook.rb +++ b/lib/stripe/webhook.rb @@ -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. @@ -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 @@ -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 @@ -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 diff --git a/test/stripe/webhook_test.rb b/test/stripe/webhook_test.rb index 07f239560..2602e09ac 100644 --- a/test/stripe/webhook_test.rb +++ b/test/stripe/webhook_test.rb @@ -52,6 +52,14 @@ class WebhookTest < Test::Unit::TestCase ) assert_equal("t=#{timestamp.to_i},#{scheme}=#{signature}", header) end + + should "include debug metadata when supplied" do + opts = { payload: EVENT_PAYLOAD, timestamp: Time.at(123), signature: "test_signature", debug_metadata: { secret: "whsec_**abcd", destination: "we_example", payload: "12345678" } } + assert_equal( + "t=123,v1=test_signature,secret=whsec_**abcd,destination=we_example,payload=12345678", + Test::WebhookHelpers.generate_header(opts) + ) + end end context ".construct_event" do @@ -152,6 +160,20 @@ class WebhookTest < Test::Unit::TestCase assert_match("No signatures found with expected scheme", e.message) end + should "raise a SignatureVerificationError when a required header value is missing or invalid" do + [ + ["t", "Unable to extract timestamp and signatures from header"], + ["t=now", "Unable to extract timestamp and signatures from header"], + ["t=now,v1=123", "Unable to extract timestamp and signatures from header"], + ["t=12345678,v1", "No signatures found with expected scheme v1"], + ].each do |header, expected_message| + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, Test::WebhookHelpers::SECRET) + end + assert_equal(expected_message, e.message) + end + end + should "raise a SignatureVerificationError when there are no valid signatures for the payload" do header = Test::WebhookHelpers.generate_header(payload: EVENT_PAYLOAD, signature: "bad_signature") e = assert_raises(Stripe::SignatureVerificationError) do @@ -222,6 +244,101 @@ class WebhookTest < Test::Unit::TestCase header = Test::WebhookHelpers.generate_header(payload: EVENT_PAYLOAD, timestamp: Time.at(12_345)) assert(Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, Test::WebhookHelpers::SECRET)) end + + context "with debug metadata" do + correct_payload_hash = OpenSSL::Digest::SHA256.hexdigest(EVENT_PAYLOAD)[-8, 8] + + should "diagnose a secret mismatch" do + header = Test::WebhookHelpers.generate_header( + payload: EVENT_PAYLOAD, + debug_metadata: { secret: "whsec_****************************1q84", destination: "we_example", payload: correct_payload_hash } + ) + secret = "whsec_abcdefghijklmnopqrstuvwxyz" + + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, secret) + end + assert_equal(<<~MESSAGE.chomp, e.message) + Webhook signature verification failed. This request may not have originated from Stripe. + + The signing secret you provided is 32 characters long and ends in `wxyz`. However, the signing secret for this destination is 38 characters long and looks like `whsec_****************************1q84`. Ensure you're using the signing secret for this destination, as shown on the Dashboard: https://dashboard.stripe.com/webhooks/we_example + + Learn more: https://docs.stripe.com/webhooks/signature + MESSAGE + end + + should "diagnose a secret mismatch with missing destination" do + header = Test::WebhookHelpers.generate_header( + payload: EVENT_PAYLOAD, + debug_metadata: { secret: "whsec_****************************1q84", payload: correct_payload_hash } + ) + secret = "whsec_abcdefghijklmnopqrstuvwxyz" + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, secret) + end + # Signing secret error shown, but without a specific event destination in the URL + assert_match(/The signing secret you provided/, e.message) + assert_match(%r{Dashboard: https://dashboard.stripe.com/webhooks\n}, e.message) + end + + should "diagnose a payload mismatch based on its hash" do + header = Test::WebhookHelpers.generate_header( + payload: EVENT_PAYLOAD, + debug_metadata: { secret: "whsec_*******cret", payload: correct_payload_hash.upcase } + ) + + # User supplies the payload with errant whitespace + user_payload = EVENT_PAYLOAD + " " + user_payload_hash = OpenSSL::Digest::SHA256.hexdigest(user_payload)[-8, 8] + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(user_payload, header, Test::WebhookHelpers::SECRET) + end + assert_equal(<<~MESSAGE.chomp, e.message) + Webhook signature verification failed. + + The request body you passed to this function differs from the request body sent by Stripe to this webhook destination. + The SHA-256 hash of the body should end in `#{correct_payload_hash}`. However, the SHA-256 hash of the body you provided ends in `#{user_payload_hash}`. + + Make sure your code does not reformat or otherwise alter the raw HTTP request body before passing it to this function. + + Learn more: https://docs.stripe.com/webhooks/signature + MESSAGE + end + + should "not show secret mismatch info, if provided with invalid metadata" do + ["whsec_unmasked", "whsec_long#{'*' * 100}long"].each do |masked_secret| + header = Test::WebhookHelpers.generate_header( + payload: EVENT_PAYLOAD, signature: "bad_signature", + debug_metadata: { secret: masked_secret, payload: correct_payload_hash } + ) + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, Test::WebhookHelpers::SECRET) + end + # Fall through to generic error + assert_equal("No signatures found matching the expected signature for payload", e.message) + end + end + + should "not show payload mismatch info, if provided with invalid metadata" do + header = Test::WebhookHelpers.generate_header( + payload: EVENT_PAYLOAD, signature: "bad_signature", + debug_metadata: { secret: "whsec_*******cret", payload: "abcde#{'f' * 100}" } + ) + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, Test::WebhookHelpers::SECRET) + end + # Fall through to generic error + assert_equal("No signatures found matching the expected signature for payload", e.message) + end + + should "ignore malformed debug key-value pairs" do + header = "t=123,v1=123456,secret,destination,payload" + e = assert_raises(Stripe::SignatureVerificationError) do + Stripe::Webhook::Signature.verify_header(EVENT_PAYLOAD, header, Test::WebhookHelpers::SECRET) + end + assert_equal("No signatures found matching the expected signature for payload", e.message) + end + end end end end diff --git a/test/test_helper.rb b/test/test_helper.rb index 3a22f2f1d..9ff846732 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -89,11 +89,15 @@ def self.generate_header(opts = {}) opts[:payload], opts[:secret] ) - Stripe::Webhook::Signature.generate_header( + header = Stripe::Webhook::Signature.generate_header( opts[:timestamp], opts[:signature], scheme: opts[:scheme] ) + debug_metadata = (opts[:debug_metadata] || {}).map do |key, value| + value.nil? ? key.to_s : "#{key}=#{value}" + end + ([header] + debug_metadata).join(",") end end end From c3cc21fae1a5fbae27cd3635683657811277cdf0 Mon Sep 17 00:00:00 2001 From: jar-stripe Date: Mon, 9 Nov 2026 19:21:36 -0800 Subject: [PATCH 2/2] Fix stripe_account and stripe_context in Event#fetch_related_object (#2022) * Fix account scoping on Event#fetch_related_object A directly-retrieved Event#fetch_related_object fell back to the retrieving client's own stripe_account instead of the event's own context, because _request's combine_opts merge re-applied the Event's retained @opts. EventNotification already avoids this by scoping its @client to the notification's context at construction time; Event now does the equivalent by routing _request through a context-scoped, account-free requestor. Fixes RUN_DEVSDK-3694 (ruby portion). Co-Authored-By: Claude Sonnet 5 Committed-By-Agent: claude * Add PR URL to event-context-scoping changefile Co-Authored-By: Claude Sonnet 5 Committed-By-Agent: claude * Update 2026-11-06_jar_fix-event-context-scoping.change.md * Update 2026-11-06_jar_fix-event-context-scoping.change.md * Move Event context-scoping into a hand-maintained EventBase Event is generated from the OpenAPI spec, so the scoped_requestor/ _request override from the previous commit lived in a generated file with no durable home across regeneration. sdk-codegen (stripe/sdk-codegen#4349) now generates `Event < EventBase` instead of `Event < APIResource`; EventBase is a new hand-maintained class, autoloaded the same way as EventNotification, that carries the scoping logic verbatim. Regenerated via `just gen ruby --repo `. Co-Authored-By: Claude Sonnet 5 Committed-By-Agent: claude * Fix retained api_key/stripe_version loss in EventBase#_request, declare EventBase RBI EventBase#_request skipped RequestOptions.combine_opts(@opts, req_opts) entirely, so a retained per-object api_key or stripe_version override (e.g. from events.retrieve(id, api_key: 'rk_restricted')) was silently dropped on fetch_related_object, falling back to the ambient requestor's default. Restores the merge, with @opts's own stripe_account/stripe_context forced to the safe values first so a stale account can't leak back in through it. Also ships a hand-maintained rbi/stripe/resources/v2/core/event_base.rbi, mirroring event_notification.rbi, since EventBase is referenced as Event's superclass in the generated RBI but was otherwise undeclared anywhere in the packaged gem. Co-Authored-By: Claude Sonnet 5 Committed-By-Agent: claude --------- Co-authored-by: Claude Sonnet 5 --- ...06_jar_fix-event-context-scoping.change.md | 9 ++ lib/stripe/resources.rb | 2 + lib/stripe/resources/v2/core/event.rb | 2 +- lib/stripe/resources/v2/core/event_base.rb | 36 ++++++++ rbi/stripe.rbi | 2 +- rbi/stripe/resources/v2/core/event.rbi | 2 +- rbi/stripe/resources/v2/core/event_base.rbi | 11 +++ stripe.gemspec | 3 +- test/stripe/v2_event_test.rb | 88 +++++++++++++++++++ 9 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 .hark/changes/2026-11-06_jar_fix-event-context-scoping.change.md create mode 100644 lib/stripe/resources/v2/core/event_base.rb create mode 100644 rbi/stripe/resources/v2/core/event_base.rbi diff --git a/.hark/changes/2026-11-06_jar_fix-event-context-scoping.change.md b/.hark/changes/2026-11-06_jar_fix-event-context-scoping.change.md new file mode 100644 index 000000000..1bb8277e0 --- /dev/null +++ b/.hark/changes/2026-11-06_jar_fix-event-context-scoping.change.md @@ -0,0 +1,9 @@ +--- +title: "Fix stripe_account and stripe_context scoping on Event#fetch_related_object" +pr_url: https://github.com/stripe/stripe-ruby/pull/2022 +semver_level: patch +jira_tickets_closed: +- RUN_DEVSDK-3694 +--- + +When fetching a related object, directly-retrieved `Event` objects used the retaining client's own `stripe_context` rather than the event's `stripe_context`. `fetch_related_object` now routes through a requestor scoped to the event's context. This mirrors how `EventNotification` scopes its client. diff --git a/lib/stripe/resources.rb b/lib/stripe/resources.rb index 7988010d4..33c6986ef 100644 --- a/lib/stripe/resources.rb +++ b/lib/stripe/resources.rb @@ -1109,6 +1109,7 @@ module Core autoload :AccountPersonToken, "stripe/resources/v2/core/account_person_token" autoload :AccountToken, "stripe/resources/v2/core/account_token" 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" @@ -1145,6 +1146,7 @@ module MoneyManagement 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 diff --git a/lib/stripe/resources/v2/core/event.rb b/lib/stripe/resources/v2/core/event.rb index 51e7d9ce7..ef954ed14 100644 --- a/lib/stripe/resources/v2/core/event.rb +++ b/lib/stripe/resources/v2/core/event.rb @@ -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" diff --git a/lib/stripe/resources/v2/core/event_base.rb b/lib/stripe/resources/v2/core/event_base.rb new file mode 100644 index 000000000..c723d4bdc --- /dev/null +++ b/lib/stripe/resources/v2/core/event_base.rb @@ -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 diff --git a/rbi/stripe.rbi b/rbi/stripe.rbi index c0fe08461..6652bd848 100644 --- a/rbi/stripe.rbi +++ b/rbi/stripe.rbi @@ -59648,7 +59648,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 # ID of the API request that caused the event. diff --git a/rbi/stripe/resources/v2/core/event.rbi b/rbi/stripe/resources/v2/core/event.rbi index b7c2d202b..ca6853738 100644 --- a/rbi/stripe/resources/v2/core/event.rbi +++ b/rbi/stripe/resources/v2/core/event.rbi @@ -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 # ID of the API request that caused the event. diff --git a/rbi/stripe/resources/v2/core/event_base.rbi b/rbi/stripe/resources/v2/core/event_base.rbi new file mode 100644 index 000000000..73b28217e --- /dev/null +++ b/rbi/stripe/resources/v2/core/event_base.rbi @@ -0,0 +1,11 @@ +# frozen_string_literal: true +# typed: true + +module Stripe + module V2 + module Core + class EventBase < APIResource + end + end + end +end diff --git a/stripe.gemspec b/stripe.gemspec index 5f982c5d4..b27c45adf 100644 --- a/stripe.gemspec +++ b/stripe.gemspec @@ -35,7 +35,8 @@ Gem::Specification.new do |s| # Handwritten RBIs # TODO(helenye): http://go/j/DEVSDK-2769 %r{\Arbi/stripe/stripe_client.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" diff --git a/test/stripe/v2_event_test.rb b/test/stripe/v2_event_test.rb index 148c8ddb3..e3f43140a 100644 --- a/test/stripe/v2_event_test.rb +++ b/test/stripe/v2_event_test.rb @@ -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")