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
Original file line number Diff line number Diff line change
@@ -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
---
19 changes: 19 additions & 0 deletions stripe/_api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions stripe/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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.
Expand Down
31 changes: 31 additions & 0 deletions tests/test_api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
60 changes: 60 additions & 0 deletions tests/test_v2_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
V1BillingMeterErrorReportTriggeredEvent,
)
from stripe.events._v1_product_updated_event import (
V1ProductUpdatedEvent,
V1ProductUpdatedEventNotification,
)
from stripe.v2.core._event import (
Expand Down Expand Up @@ -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
Loading