diff --git a/.hark/changes/2026-11-06_jar_fix-event-related-object-account-scoping.change.md b/.hark/changes/2026-11-06_jar_fix-event-related-object-account-scoping.change.md new file mode 100644 index 000000000..027e2fb54 --- /dev/null +++ b/.hark/changes/2026-11-06_jar_fix-event-related-object-account-scoping.change.md @@ -0,0 +1,6 @@ +--- +title: Fix stale Stripe-Account header when fetching an object related to a directly-retrieved Event +semver_level: patch +jira_tickets_closed: +- RUN_DEVSDK-3694 +--- diff --git a/stripe/_api_requestor.py b/stripe/_api_requestor.py index 6224c5e6d..a9a52c09d 100644 --- a/stripe/_api_requestor.py +++ b/stripe/_api_requestor.py @@ -65,6 +65,7 @@ if TYPE_CHECKING: from stripe._app_info import AppInfo from stripe._stripe_object import StripeObject + from stripe._stripe_context import StripeContext HttpVerb = Literal["get", "post", "delete"] @@ -174,6 +175,24 @@ def _new_requestor_with_options( options=RequestorOptions(**new_options), client=self._client ) + def with_stripe_context( + self, stripe_context: "Optional[Union[str, StripeContext]]" + ) -> "_APIRequestor": + """ + Returns a new _APIRequestor with the same configuration as this one, but + scoped to a different stripe_context. Unlike _new_requestor_with_options, + this always replaces stripe_context (even with None) and clears + stripe_account, since a context is self-contained and a stripe_account + inherited from whatever request produced this requestor should not leak + into requests scoped by it. + """ + new_options = self._options.to_dict() + new_options["stripe_context"] = stripe_context + new_options["stripe_account"] = None + return _APIRequestor( + options=RequestorOptions(**new_options), client=self._client + ) + @property def api_key(self): return self._options.api_key diff --git a/stripe/_util.py b/stripe/_util.py index e034b209f..995967aa5 100644 --- a/stripe/_util.py +++ b/stripe/_util.py @@ -243,6 +243,7 @@ def _convert_to_stripe_object( elif isinstance(resp, dict): resp = resp.copy() klass_name = resp.get("object") + requestor_uses_response_context = False if isinstance(klass_name, str): if is_v2_deleted_object: # circular import @@ -254,6 +255,7 @@ def _convert_to_stripe_object( event_type = resp.get("type", "") klass = get_v2_event_class(event_type) + requestor_uses_response_context = True else: from stripe._object_classes import get_object_class @@ -279,6 +281,17 @@ def _convert_to_stripe_object( api_mode=api_mode, ) + if requestor_uses_response_context: + # A directly-retrieved object carries the requestor of whatever + # account fetched it (e.g. a platform account), but its `context` + # field is the self-contained auth context for its own account. + # Rescope the requestor the same way EventNotification.__init__ + # scopes its client so fetch_related_object() uses the correct + # headers. + obj._requestor = obj._requestor.with_stripe_context( + getattr(obj, "context", None) + ) + # We only need to update _retrieve_params when special params were # actually passed. Otherwise, leave it as is as the list / search result # constructors will instantiate their own params. diff --git a/tests/test_api_requestor.py b/tests/test_api_requestor.py index 744930ed9..b8adae3a3 100644 --- a/tests/test_api_requestor.py +++ b/tests/test_api_requestor.py @@ -669,6 +669,37 @@ def test_uses_instance_context(self, http_client_mock): stripe_context=context, ) + def test_with_stripe_context_clears_stripe_account( + self, requestor, http_client_mock: HTTPClientMock + ): + """ + with_stripe_context is used to scope a requestor to a v2 Event's own + context (see Event's construction in _util._convert_to_stripe_object). + Unlike _new_requestor_with_options, it must always clear stripe_account, + even though one was already set, so a stale account from whatever + request produced the original requestor can't leak into requests made + with the new one. + """ + requestor = requestor._new_requestor_with_options( + RequestOptions(stripe_account="acct_original") + ) + + requestor = requestor.with_stripe_context("acct_context") + + http_client_mock.stub_request( + "get", path=self.v1_path, rbody="{}", rcode=200 + ) + + requestor.request("get", self.v1_path, {}, base_address="api") + + http_client_mock.assert_requested( + "get", + stripe_context="acct_context", + ) + call = http_client_mock.get_last_call() + assert call.headers is not None + assert "Stripe-Account" not in call.headers + def test_sets_default_http_client(self, mocker): assert not stripe.default_http_client diff --git a/tests/test_v2_event.py b/tests/test_v2_event.py index 7f59ca3d5..ea7c46c95 100644 --- a/tests/test_v2_event.py +++ b/tests/test_v2_event.py @@ -15,6 +15,7 @@ V1BillingMeterErrorReportTriggeredEvent, ) from stripe.events._v1_product_updated_event import ( + V1ProductUpdatedEvent, V1ProductUpdatedEventNotification, ) from stripe.v2.core._event import ( @@ -515,3 +516,62 @@ async def test_related_object_retains_event_context_async( http_client_mock.assert_requested( "delete", path=path, stripe_context="acct_child" ) + + def test_direct_retrieve_related_object_retains_event_context( + self, http_client_mock: HTTPClientMock + ): + """ + Unlike EventNotification (built from a webhook), a directly-retrieved + Event doesn't go through StripeClient.with_stripe_context in its own + construction, so historically it kept whatever stripe_account retrieved + it. Make sure fetch_related_object() only ever uses the event's own + context, with no stale account from the retrieving client leaking in. + """ + event_path = "/v2/core/events/evt_123" + related_path = "/v1/products/prod_shared" + + http_client_mock.stub_request( + "get", + path=event_path, + rbody=json.dumps( + { + "id": "evt_123", + "object": "v2.core.event", + "type": "v1.product.updated", + "created": "2022-02-15T00:27:45.330Z", + "livemode": False, + "context": "acct_child", + "related_object": { + "id": "prod_shared", + "type": "product", + "url": related_path, + }, + } + ), + ) + http_client_mock.stub_request( + "get", + path=related_path, + rbody=json.dumps({"id": "prod_shared", "object": "product"}), + ) + + client = StripeClient( + api_key="sk_test_1234", + stripe_account="acct_platform", + http_client=http_client_mock.get_mock_http_client(), + ) + + event = client.v2.core.events.retrieve("evt_123") + assert isinstance(event, V1ProductUpdatedEvent) + + product = event.fetch_related_object() + assert product.id == "prod_shared" + + http_client_mock.assert_requested( + "get", path=related_path, stripe_context="acct_child" + ) + + assert len(http_client_mock.get_all_calls()) == 2 + related_call = http_client_mock.get_last_call() + assert related_call.headers is not None + assert "Stripe-Account" not in related_call.headers