Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
78952be
[🪿] Omit API keys from StripeObject pickles
zacchua-stripe Oct 30, 2026
c11d090
[🪿] try to deslop
zacchua-stripe Oct 30, 2026
096a7e3
[🪿] Align pickle credential migration with v17
zacchua-stripe Oct 30, 2026
e34a040
[🪿] try to deslop
zacchua-stripe Oct 30, 2026
d7c529d
[🪿] Update PyPI publishing action to v1.14.3
zacchua-stripe Oct 30, 2026
427f81f
[🪿] Revert unrelated PyPI publishing action upgrade
zacchua-stripe Oct 30, 2026
9391eec
[🪿] Update pickle credential changefile wording and filename
zacchua-stripe Oct 30, 2026
d0bef0d
[🪿] Simplify v17 pickle migration guidance
zacchua-stripe Oct 30, 2026
af9487d
[🪿] Replace set_api_key with per-call API keys on instance methods
zacchua-stripe Nov 3, 2026
b57fe37
[🪿] Trim pickle credential changefile wording
zacchua-stripe Nov 3, 2026
53638b6
Merge branch 'master' into fix/pickle-credentials
zacchua-stripe Nov 3, 2026
b3a10a9
Require explicit API key reattachment after unpickling
zacchua-stripe Nov 5, 2026
1c9e204
Keep serialized placeholders in requestors and guard requests centrally
zacchua-stripe Nov 5, 2026
ee7b14b
Clarify API key reattachment wording in changefile
zacchua-stripe Nov 5, 2026
276b7ab
Clarify API key reattachment migration guidance
zacchua-stripe Nov 6, 2026
131602e
Address serialization documentation review feedback
zacchua-stripe Nov 6, 2026
f6c8de4
Make migration guide before/after examples equivalent
zacchua-stripe Nov 10, 2026
fc1d7b3
Merge branch 'sdk-release/next-major' into fix/pickle-credentials
zacchua-stripe Nov 10, 2026
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,7 @@
---
title: Omit API keys from pickled StripeObjects
Comment thread
jar-stripe marked this conversation as resolved.
Resolved
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.
37 changes: 37 additions & 0 deletions .hark/migration-guides/v17.md
Original file line number Diff line number Diff line change
@@ -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.
13 changes: 13 additions & 0 deletions stripe/_api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. "
Comment thread
jar-stripe marked this conversation as resolved.
Resolved
"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:
Expand Down Expand Up @@ -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:
Expand Down
49 changes: 48 additions & 1 deletion stripe/_stripe_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
Expand Down Expand Up @@ -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:
Comment thread
jar-stripe marked this conversation as resolved.
Resolved
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
Expand Down Expand Up @@ -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,
),
Expand Down
91 changes: 91 additions & 0 deletions tests/api_resources/test_list_object.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import pickle

import pytest

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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(
Expand Down
28 changes: 28 additions & 0 deletions tests/api_resources/test_list_object_v2.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, print_function

import json
import pickle

import pytest

Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions tests/api_resources/test_search_result_object.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import pickle

import pytest

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading