diff --git a/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md b/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md new file mode 100644 index 000000000..76dc33045 --- /dev/null +++ b/.hark/changes/2026-10-30_zacchua_omit-pickled-api-keys.change.md @@ -0,0 +1,7 @@ +--- +title: Omit API keys from pickled StripeObjects +semver_level: major +--- +StripeObject pickles no longer preserve API keys. Before making requests through an unpickled object, call `reattach_api_key(api_key)`. This also reattaches API keys to nested objects. + +See the [v17 migration guide](https://github.com/stripe/stripe-python/blob/master/.hark/migration-guides/v17.md#api-keys-are-no-longer-preserved-in-pickled-stripeobjects) for details. diff --git a/.hark/migration-guides/v17.md b/.hark/migration-guides/v17.md new file mode 100644 index 000000000..a7a654b8c --- /dev/null +++ b/.hark/migration-guides/v17.md @@ -0,0 +1,37 @@ +# Migration guide for v17 +## API keys are no longer preserved in pickled StripeObjects +This affects integrations that persist StripeObjects in caches or queues and then make requests through the restored objects. + +Pickling now replaces API keys with a placeholder, including on nested objects. Unpickled objects retain their data, connected-account routing, and API version but have no API key. Before making requests through an unpickled object, call `reattach_api_key()` with a key from secure configuration: + +```python +# Before +customer = pickle.loads(trusted_cached_bytes) +customer.refresh() + +# After +customer = pickle.loads(trusted_cached_bytes) +customer.reattach_api_key(api_key) +customer.refresh() +``` + +Reattach the API key the same way on unpickled lists and events before making requests through them: + +```python +customers = pickle.loads(trusted_cached_list_bytes) +customers.reattach_api_key(api_key) +for customer in customers.auto_paging_iter(): + ... + +event = pickle.loads(trusted_cached_event_bytes) +event.reattach_api_key(api_key) +related_object = event.fetch_related_object() +``` + +`reattach_api_key()` also attaches API keys to nested unpickled objects. Each retains its saved API version and connected account. Nested objects that already have an API key keep it. Reattachment does not change `stripe.api_key`, and pickling the object again omits the reattached key. + +Requests before reattachment raise `AuthenticationError` with instructions to call `reattach_api_key()`, even if you set a global or per-call API key. + +Calling `reattach_api_key()` more than once, or on an object whose API key wasn't replaced with the serialization placeholder, raises `ValueError`. Passing an empty key or the serialization placeholder also raises `ValueError`. + +This behavior applies to pickles created with v17. Pickles created with earlier versions can still contain API keys. Remove or replace those stored pickles according to your application's storage policy. diff --git a/stripe/_api_requestor.py b/stripe/_api_requestor.py index 6224c5e6d..9d0bd36e6 100644 --- a/stripe/_api_requestor.py +++ b/stripe/_api_requestor.py @@ -61,6 +61,7 @@ from stripe._base_address import BaseAddress from stripe._api_mode import ApiMode +from stripe._stripe_object import API_KEY_SERIALIZATION_CONSTANT if TYPE_CHECKING: from stripe._app_info import AppInfo @@ -165,6 +166,12 @@ def _new_requestor_with_options( """ Returns a new _APIRequestor instance with the same HTTP client but a (potentially) updated set of options. Useful for ensuring the original isn't modified, but any options the original had are still used. """ + if self.api_key == API_KEY_SERIALIZATION_CONSTANT: + raise error.AuthenticationError( + "This object was unpickled without API credentials. " + "Call reattach_api_key(api_key) on the object before making requests." + ) + options = options or {} new_options = self._options.to_dict() for key in PERSISTENT_OPTIONS_KEYS: @@ -673,6 +680,12 @@ def _args_for_request_with_retries( """ Mechanism for issuing an API call. Used by request_raw and request_raw_async. """ + if self.api_key == API_KEY_SERIALIZATION_CONSTANT: + raise error.AuthenticationError( + "This object was unpickled without API credentials. " + "Call reattach_api_key(api_key) on the object before making requests." + ) + request_options = merge_options(self._options, options) # Special stripe_version handling for v2 requests: diff --git a/stripe/_stripe_object.py b/stripe/_stripe_object.py index 8fe6d87d7..56ac30eb8 100644 --- a/stripe/_stripe_object.py +++ b/stripe/_stripe_object.py @@ -49,6 +49,9 @@ from stripe._api_requestor import _APIRequestor # pyright: ignore[reportPrivateUsage] +API_KEY_SERIALIZATION_CONSTANT = "API_KEY_SERIALIZATION_CONSTANT" + + @overload def _compute_diff( current: Dict[str, Any], previous: Optional[Dict[str, Any]] @@ -156,6 +159,50 @@ def stripe_account(self): def stripe_version(self): return self._requestor.stripe_version + def reattach_api_key(self, api_key: str) -> None: + """Attach credentials to an unpickled object and its nested objects. + + Each object retains its saved API version and connected account. + Objects that already have credentials cannot be reattached. + """ + if self.api_key != API_KEY_SERIALIZATION_CONSTANT: + raise ValueError( + "API credentials can only be reattached to an unpickled " + "object that has not already been reattached." + ) + if ( + not isinstance(cast(object, api_key), str) + or not api_key.strip() + or api_key == API_KEY_SERIALIZATION_CONSTANT + ): + raise ValueError("api_key must be a non-empty, valid API key.") + + from stripe._api_requestor import _APIRequestor # pyright: ignore[reportPrivateUsage] + + seen: Set[int] = set() + + def reattach(value: Any) -> None: + if id(value) in seen: + return + seen.add(id(value)) + if isinstance(value, StripeObject): + if value.api_key == API_KEY_SERIALIZATION_CONSTANT: + value._requestor = _APIRequestor._global_with_options( # pyright: ignore[reportPrivateUsage] + api_key=api_key, + stripe_version=value.stripe_version, + stripe_account=value.stripe_account, + ) + for nested in value._data.values(): + reattach(nested) + elif isinstance(value, dict): + for nested in cast(Dict[Any, Any], value).values(): + reattach(nested) + elif isinstance(value, (list, tuple)): + for nested in cast(Union[List[Any], Tuple[Any, ...]], value): + reattach(nested) + + reattach(self) + @property def last_response(self) -> Optional[StripeResponse]: return self._last_response @@ -298,7 +345,7 @@ def __reduce__(self) -> Tuple[Any, ...]: type(self), # callable ( # args getattr(self, "id", None), - self.api_key, + API_KEY_SERIALIZATION_CONSTANT, self.stripe_version, self.stripe_account, ), diff --git a/tests/api_resources/test_list_object.py b/tests/api_resources/test_list_object.py index 02568c4b7..895094d36 100644 --- a/tests/api_resources/test_list_object.py +++ b/tests/api_resources/test_list_object.py @@ -1,4 +1,5 @@ import json +import pickle import pytest @@ -297,6 +298,68 @@ def test_iter_two_pages(self, http_client_mock): assert seen == ["pm_123", "pm_124", "pm_125", "pm_126"] + @pytest.fixture + def restored_list(self, monkeypatch): + lo = stripe.ListObject.construct_from( + self.pageable_model_response(["pm_123"], True), + "producer-key-sentinel", + stripe_account="example-account", + ) + monkeypatch.setattr(stripe, "api_key", None) + restored = pickle.loads(pickle.dumps(lo)) + restored.reattach_api_key("worker-key-sentinel") + return restored + + def test_iter_uses_reattached_api_key_on_every_page( + self, http_client_mock, restored_list + ): + http_client_mock.stub_request( + "get", + path="/v1/pageablemodels", + query_string="starting_after=pm_123", + rbody=json.dumps(self.pageable_model_response(["pm_124"], True)), + ) + http_client_mock.stub_request( + "get", + path="/v1/pageablemodels", + query_string="starting_after=pm_124", + rbody=json.dumps(self.pageable_model_response(["pm_125"], False)), + ) + + seen = [item["id"] for item in restored_list.auto_paging_iter()] + + assert seen == ["pm_123", "pm_124", "pm_125"] + for starting_after in ("pm_123", "pm_124"): + http_client_mock.assert_requested( + "get", + path="/v1/pageablemodels", + query_string=f"starting_after={starting_after}", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + + def test_iter_reverse_uses_reattached_api_key( + self, http_client_mock, restored_list + ): + restored_list._retrieve_params = {"ending_before": "pm_124"} + http_client_mock.stub_request( + "get", + path="/v1/pageablemodels", + query_string="ending_before=pm_123", + rbody=json.dumps(self.pageable_model_response(["pm_122"], False)), + ) + + seen = [item["id"] for item in restored_list.auto_paging_iter()] + + assert seen == ["pm_123", "pm_122"] + http_client_mock.assert_requested( + "get", + path="/v1/pageablemodels", + query_string="ending_before=pm_123", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + def test_iter_reverse(self, http_client_mock): lo = stripe.ListObject.construct_from( self.pageable_model_response(["pm_125", "pm_126"], True), "mykey" @@ -655,6 +718,34 @@ async def test_iter_one_page(self, http_client_mock): assert seen == ["pm_123", "pm_124"] + @pytest.mark.anyio + async def test_iter_uses_reattached_api_key( + self, http_client_mock, monkeypatch + ): + lo = stripe.ListObject.construct_from( + self.pageable_model_response(["pm_123"], True), + "producer-key-sentinel", + ) + monkeypatch.setattr(stripe, "api_key", None) + restored = pickle.loads(pickle.dumps(lo)) + restored.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/pageablemodels", + query_string="starting_after=pm_123", + rbody=json.dumps(self.pageable_model_response(["pm_124"], False)), + ) + + seen = [item["id"] async for item in restored.auto_paging_iter()] + + assert seen == ["pm_123", "pm_124"] + http_client_mock.assert_requested( + "get", + path="/v1/pageablemodels", + query_string="starting_after=pm_123", + api_key="worker-key-sentinel", + ) + @pytest.mark.anyio async def test_iter_two_pages(self, http_client_mock): lo = stripe.ListObject.construct_from( diff --git a/tests/api_resources/test_list_object_v2.py b/tests/api_resources/test_list_object_v2.py index 84759e873..a7581b142 100644 --- a/tests/api_resources/test_list_object_v2.py +++ b/tests/api_resources/test_list_object_v2.py @@ -1,6 +1,7 @@ from __future__ import absolute_import, division, print_function import json +import pickle import pytest @@ -147,6 +148,33 @@ def test_iter_forwards_api_key(self, http_client_mock: HTTPClientMock): api_key="sk_test_iter_forwards_options", ) + def test_iter_uses_reattached_api_key(self, http_client_mock, monkeypatch): + lo = ListObject.construct_from( + self.pageable_model_response( + ["pm_123"], "/v2/pageablemodels?page=page_2" + ), + "producer-key-sentinel", + ) + monkeypatch.setattr(stripe, "api_key", None) + restored = pickle.loads(pickle.dumps(lo)) + restored.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v2/pageablemodels", + query_string="page=page_2", + rbody=json.dumps(self.pageable_model_response(["pm_124"], None)), + ) + + seen = [item["id"] for item in restored.auto_paging_iter()] + + assert seen == ["pm_123", "pm_124"] + http_client_mock.assert_requested( + "get", + path="/v2/pageablemodels", + query_string="page=page_2", + api_key="worker-key-sentinel", + ) + class TestAutoPagingAsync: @staticmethod diff --git a/tests/api_resources/test_search_result_object.py b/tests/api_resources/test_search_result_object.py index 9db977921..5d640e374 100644 --- a/tests/api_resources/test_search_result_object.py +++ b/tests/api_resources/test_search_result_object.py @@ -1,4 +1,5 @@ import json +import pickle import pytest @@ -256,6 +257,35 @@ def test_iter_two_pages(self, http_client_mock): assert seen == ["pm_123", "pm_124", "pm_125", "pm_126"] + def test_iter_uses_reattached_api_key(self, http_client_mock, monkeypatch): + sro = stripe.SearchResultObject.construct_from( + self.pageable_model_response(["pm_123"], True, "token"), + "producer-key-sentinel", + stripe_account="example-account", + ) + monkeypatch.setattr(stripe, "api_key", None) + restored = pickle.loads(pickle.dumps(sro)) + restored.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/pageablemodels", + query_string="page=token", + rbody=json.dumps( + self.pageable_model_response(["pm_124"], False, None) + ), + ) + + seen = [item["id"] for item in restored.auto_paging_iter()] + + assert seen == ["pm_123", "pm_124"] + http_client_mock.assert_requested( + "get", + path="/v1/pageablemodels", + query_string="page=token", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + class TestAutoPagingAsync: @staticmethod diff --git a/tests/test_stripe_object.py b/tests/test_stripe_object.py index aecd64938..6873b915a 100644 --- a/tests/test_stripe_object.py +++ b/tests/test_stripe_object.py @@ -8,7 +8,7 @@ import stripe from stripe._invoice import Invoice -from stripe._stripe_object import StripeObject +from stripe._stripe_object import API_KEY_SERIALIZATION_CONSTANT, StripeObject # We use this because it has a map, "restriction.currency_options" from string -> CurrencyOptions nested class. SAMPLE_PROMOTION_CODE = json.loads( @@ -274,30 +274,365 @@ def test_repr(self): assert '"date": 1511136000' in res assert '"dec": "1.23"' in res - def test_pickling(self): - obj = StripeObject("foo", "bar", myparam=5) - - obj["object"] = "boo" - obj.refresh_from( + @pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1)) + @pytest.mark.parametrize( + "destination_key", [None, "destination-key-sentinel"] + ) + def test_pickling(self, protocol, destination_key, monkeypatch): + obj = stripe.Customer.construct_from( { - "fala": "lalala", - # ensures that empty strings are correctly unpickled in Py3 - "emptystring": "", + "id": "resource", + "object": "customer", + "description": "example", + "metadata": {"emptystring": ""}, }, - api_key="bar", - partial=True, + "producer-key-sentinel", + stripe_version="2017-08-15", + stripe_account="example-account", + ) + obj.metadata.api_key = "nested-key-sentinel" + nested = stripe.Customer.construct_from( + {"id": "nested-resource", "object": "customer"}, + "nested-key-sentinel", + stripe_version="2018-02-28", + stripe_account="nested-example-account", + ) + obj.containers = [{"nested": nested}] + original_requestor = obj._requestor + payload = obj.to_dict() + + for value in (obj.metadata, obj): + assert value.__reduce__()[1][1] == API_KEY_SERIALIZATION_CONSTANT + pickled = pickle.dumps(value, protocol=protocol) + assert b"producer-key-sentinel" not in pickled + assert b"nested-key-sentinel" not in pickled + + monkeypatch.setattr(stripe, "api_key", destination_key) + restored = pickle.loads(pickled) + + assert type(restored) is stripe.Customer + assert restored.to_dict() == payload + for value in (restored, restored.metadata): + assert value.api_key == API_KEY_SERIALIZATION_CONSTANT + assert value.stripe_version == "2017-08-15" + assert value.stripe_account == "example-account" + assert obj.api_key == "producer-key-sentinel" + assert obj.metadata.api_key == "nested-key-sentinel" + assert obj._requestor is original_requestor + assert obj.to_dict() == payload + + restored_nested = restored.containers[0]["nested"] + assert restored_nested.api_key == API_KEY_SERIALIZATION_CONSTANT + assert restored_nested.stripe_account == "nested-example-account" + assert restored_nested.stripe_version == "2018-02-28" + + restored.reattach_api_key("reattached-key-sentinel") + for value in (restored, restored.metadata, restored_nested): + assert value.api_key == "reattached-key-sentinel" + assert restored_nested.stripe_account == "nested-example-account" + assert restored_nested.stripe_version == "2018-02-28" + assert stripe.api_key == destination_key + + pickled = pickle.dumps(restored, protocol=protocol) + for key in ( + b"producer-key-sentinel", + b"nested-key-sentinel", + b"destination-key-sentinel", + b"reattached-key-sentinel", + ): + assert key not in pickled + + def test_pickling_verified_webhook(self, monkeypatch): + payload = json.dumps( + { + "object": "event", + "data": { + "object": {"object": "customer", "metadata": {"empty": ""}} + }, + } ) + monkeypatch.setattr(stripe, "api_key", "producer-key-sentinel") + signature = stripe.WebhookSignature.generate_signature_header( + payload, "webhook-test-secret" + ) + event = stripe.Webhook.construct_event( + payload, signature, "webhook-test-secret" + ) + pickled = pickle.dumps(event) + assert b"producer-key-sentinel" not in pickled + monkeypatch.setattr(stripe, "api_key", "destination-key-sentinel") + restored = pickle.loads(pickled) + + assert type(restored) is stripe.Event + assert type(restored.data.object) is stripe.Customer + assert restored.to_dict() == event.to_dict() + for value in ( + restored, + restored.data, + restored.data.object, + restored.data.object.metadata, + ): + assert value.api_key == API_KEY_SERIALIZATION_CONSTANT + assert event.api_key == "producer-key-sentinel" - assert obj.fala == "lalala" + @pytest.fixture + def restored_customer(self, monkeypatch): + obj = stripe.Customer.construct_from( + {"id": "resource", "object": "customer"}, + "producer-key-sentinel", + stripe_account="example-account", + ) + monkeypatch.setattr(stripe, "api_key", None) + return pickle.loads(pickle.dumps(obj)) + + @pytest.mark.parametrize("global_key", [None, "global-key-sentinel"]) + @pytest.mark.parametrize("per_call_key", [None, "per-call-key-sentinel"]) + def test_restored_delete_requires_reattachment( + self, + http_client_mock, + restored_customer, + monkeypatch, + global_key, + per_call_key, + ): + monkeypatch.setattr(stripe, "api_key", global_key) + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + restored_customer.delete(api_key=per_call_key) + http_client_mock.assert_no_request() + + def test_reattach_api_key(self, http_client_mock, restored_customer): + restored_customer.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer"}', + ) + restored_customer.refresh() + http_client_mock.assert_requested( + "get", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + assert ( + pickle.loads(pickle.dumps(restored_customer)).api_key + == API_KEY_SERIALIZATION_CONSTANT + ) - pickled = pickle.dumps(obj) - newobj = pickle.loads(pickled) + @pytest.mark.parametrize( + "key", [None, "", " ", 123, API_KEY_SERIALIZATION_CONSTANT] + ) + def test_reattach_api_key_rejects_invalid_keys( + self, restored_customer, key + ): + with pytest.raises(ValueError, match="api_key"): + restored_customer.reattach_api_key(key) + assert restored_customer.api_key == API_KEY_SERIALIZATION_CONSTANT + + def test_reattach_api_key_rejects_attached_objects( + self, restored_customer + ): + with pytest.raises(ValueError, match="only be reattached"): + stripe.Customer("cus_123").reattach_api_key("key") + restored_customer.reattach_api_key("key") + with pytest.raises(ValueError, match="only be reattached"): + restored_customer.reattach_api_key("other-key") + assert restored_customer.api_key == "key" + + def test_reattach_api_key_handles_cycles_and_attached_children( + self, restored_customer + ): + attached = StripeObject(api_key="child-key") + restored_customer._data["nested"] = [ + restored_customer, + {"attached": attached}, + ] + restored_customer.reattach_api_key("key") + assert restored_customer.api_key == "key" + assert attached.api_key == "child-key" + + @pytest.mark.parametrize("copy_method", [copy, deepcopy]) + def test_copy_detached_object( + self, restored_customer, monkeypatch, copy_method + ): + monkeypatch.setattr(stripe, "api_key", "global-key") + copied = copy_method(restored_customer) + assert copied.api_key == API_KEY_SERIALIZATION_CONSTANT + assert copied.stripe_account == "example-account" + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + copied._request( + "get", "/v1/customers/resource", base_address="api" + ) + + @pytest.mark.parametrize("method", ["_request", "_request_stream"]) + @pytest.mark.parametrize("per_call_key", [None, "per-call-key-sentinel"]) + def test_detached_request_guard( + self, restored_customer, method, http_client_mock, per_call_key + ): + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + getattr(restored_customer, method)( + "get", + "/v1/customers/resource", + params={"api_key": per_call_key}, + ) + http_client_mock.assert_no_request() - assert newobj.id == "foo" - assert newobj.api_key == "bar" - assert newobj["object"] == "boo" - assert newobj.fala == "lalala" - assert newobj.emptystring == "" + @pytest.mark.anyio + @pytest.mark.parametrize( + "method", ["_request_async", "_request_stream_async"] + ) + @pytest.mark.parametrize("per_call_key", [None, "per-call-key-sentinel"]) + async def test_detached_async_request_guard( + self, restored_customer, method, http_client_mock, per_call_key + ): + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + await getattr(restored_customer, method)( + "get", + "/v1/customers/resource", + params={"api_key": per_call_key}, + ) + http_client_mock.assert_no_request() + + def test_detached_option_setters_require_reattachment( + self, restored_customer + ): + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + restored_customer.api_key = "key" + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + restored_customer.refresh_from({}, api_key="key") + + def test_restored_refresh_uses_reattached_api_key( + self, http_client_mock, restored_customer + ): + restored_customer.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer", "description": "refreshed"}', + ) + + assert restored_customer.refresh() is restored_customer + + http_client_mock.assert_requested( + "get", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + assert restored_customer.description == "refreshed" + assert stripe.api_key is None + assert b"worker-key-sentinel" not in pickle.dumps(restored_customer) + + @pytest.mark.anyio + async def test_restored_refresh_async_uses_reattached_api_key( + self, http_client_mock, restored_customer + ): + restored_customer.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer"}', + ) + + await restored_customer.refresh_async() + + http_client_mock.assert_requested( + "get", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + + def test_refresh_preserves_retrieve_params(self, http_client_mock): + obj = stripe.Customer( + "resource", "producer-key-sentinel", expand=["sources"] + ) + http_client_mock.stub_request( + "get", + path="/v1/customers/resource", + query_string="expand[0]=sources", + rbody='{"id": "resource", "object": "customer"}', + ) + + obj.refresh() + + http_client_mock.assert_requested( + "get", + path="/v1/customers/resource", + query_string="expand[0]=sources", + api_key="producer-key-sentinel", + ) + + def test_restored_save_uses_reattached_api_key( + self, http_client_mock, restored_customer + ): + restored_customer.reattach_api_key("worker-key-sentinel") + restored_customer.description = "changed" + http_client_mock.stub_request( + "post", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer", "description": "changed"}', + ) + + restored_customer.save() + + http_client_mock.assert_requested( + "post", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) + + def test_save_keeps_positional_idempotency_key( + self, http_client_mock, restored_customer + ): + restored_customer.reattach_api_key("worker-key-sentinel") + restored_customer.description = "changed" + http_client_mock.stub_request( + "post", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer", "description": "changed"}', + ) + + restored_customer.save("idempotency-sentinel") + + http_client_mock.assert_requested( + "post", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + idempotency_key="idempotency-sentinel", + ) + + def test_restored_delete_uses_reattached_api_key( + self, http_client_mock, restored_customer + ): + restored_customer.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "delete", + path="/v1/customers/resource", + rbody='{"id": "resource", "object": "customer", "deleted": true}', + ) + + restored_customer.delete(api_key="worker-key-sentinel") + + http_client_mock.assert_requested( + "delete", + path="/v1/customers/resource", + api_key="worker-key-sentinel", + stripe_account="example-account", + ) def test_deletion(self): obj = StripeObject("id", "key") diff --git a/tests/test_v2_event.py b/tests/test_v2_event.py index 7f59ca3d5..7353821ff 100644 --- a/tests/test_v2_event.py +++ b/tests/test_v2_event.py @@ -1,4 +1,6 @@ import json +import pickle +import stripe from typing import Any, Callable, Dict, Optional, Union from typing_extensions import assert_type @@ -38,6 +40,32 @@ class TestV2Event(object): + def test_pickled_event_requires_reattachment( + self, http_client_mock, v2_payload_no_data + ): + event = V1BillingMeterErrorReportTriggeredEvent.construct_from( + json.loads(v2_payload_no_data), "producer-key-sentinel" + ) + restored = pickle.loads(pickle.dumps(event)) + with pytest.raises( + stripe.AuthenticationError, match="reattach_api_key" + ): + restored.fetch_related_object() + http_client_mock.assert_no_request() + restored.reattach_api_key("worker-key-sentinel") + http_client_mock.stub_request( + "get", + path="/v1/billing/meters/mtr_123", + rbody='{"id": "mtr_123", "object": "billing.meter"}', + ) + restored.fetch_related_object() + http_client_mock.assert_requested( + "get", + path="/v1/billing/meters/mtr_123", + api_key="worker-key-sentinel", + stripe_context="acct_123", + ) + @pytest.fixture(scope="function") def v2_payload_no_data(self): return json.dumps(