diff --git a/.hark/changes/2026-11-26_stripe-openapi_901b303d.change.md b/.hark/changes/2026-11-26_stripe-openapi_901b303d.change.md new file mode 100644 index 000000000..80398f34e --- /dev/null +++ b/.hark/changes/2026-11-26_stripe-openapi_901b303d.change.md @@ -0,0 +1,8 @@ +--- +title: Update generated code +pr_url: https://github.com/stripe/stripe-python/pull/2003 +semver_level: minor +is_stripe_api_change: true +--- + +* Release specs are identical. diff --git a/CODEGEN_VERSION b/CODEGEN_VERSION index 06a01d0ea..89eff90a3 100644 --- a/CODEGEN_VERSION +++ b/CODEGEN_VERSION @@ -1 +1 @@ -f3581f76eec818aa658fd9635eaf0107d13e3441 \ No newline at end of file +11a5de5a2b74f8ec75d8f9419c1af77869b2f21e \ No newline at end of file diff --git a/stripe/_encode.py b/stripe/_encode.py index 7c402cf52..3db7eadc9 100644 --- a/stripe/_encode.py +++ b/stripe/_encode.py @@ -1,5 +1,6 @@ import calendar import datetime +import math import time from collections import OrderedDict from decimal import Decimal @@ -16,6 +17,13 @@ def _encode_datetime(dttime: datetime.datetime): def _encode_decimal(dec) -> str: + # str() uses exponent notation for small and large values (str(0.00001) is + # "1e-05" and str(Decimal("0.0000001")) is "1E-7"), which the API rejects. + if isinstance(dec, float) and math.isfinite(dec): + # repr() keeps the float's shortest round-trip digits, so 0.1 stays "0.1" + dec = Decimal(repr(dec)) + if isinstance(dec, Decimal) and dec.is_finite(): + return format(dec, "f") return str(dec) @@ -171,6 +179,10 @@ def _api_encode( ) for k, v in _api_encode(subdict): yield (k, v) + elif isinstance(sv, datetime.datetime): + yield (encoded_key, _encode_datetime(sv)) + elif isinstance(sv, bool): + yield (encoded_key, str(sv).lower()) else: yield (encoded_key, sv) elif isinstance(value, dict) or hasattr(value, "_data"): diff --git a/stripe/_util.py b/stripe/_util.py index 995967aa5..5de42531f 100644 --- a/stripe/_util.py +++ b/stripe/_util.py @@ -7,7 +7,7 @@ from stripe._api_mode import ApiMode -from urllib.parse import quote_plus, urlsplit +from urllib.parse import quote_plus, unquote, urlsplit from typing_extensions import Type, TYPE_CHECKING from typing import ( @@ -379,6 +379,16 @@ def validate_path(path: str) -> None: So, we require that a path starts with a leading slash and that urlsplit finds no scheme or authority in it. + + We also reject "." and ".." path segments. HTTP clients such as httpx, + requests and aiohttp remove them before sending, so an ID of "." or ".." + changes which endpoint is called: retrieving "." from + /v1/checkout/sessions/{session} lists every session instead. IDs are + escaped with quote_plus, which leaves dots alone, and some clients decode + "%2E" back to "." before removing it, so we check the decoded segment. An + encoded slash ("%2F") also counts as a separator for this check, because a + proxy that decodes the path before normalizing it (nginx's proxy_pass, for + example) turns it into a real one. """ if not path.startswith("/") or path.startswith("//"): raise ValueError( @@ -391,6 +401,14 @@ def validate_path(path: str) -> None: f"Request path may not contain a scheme or authority, got: {path!r}" ) + for segment in re.split(r"/|%2[fF]", parts.path): + if unquote(segment) in (".", ".."): + # The message leaves out the query string, which can carry + # secrets such as a client_secret. + raise ValueError( + f'Request path may not contain a "." or ".." segment, got: {parts.path!r}' + ) + def get_api_mode(url: str) -> ApiMode: if url.startswith("/v2"): diff --git a/tests/test_api_requestor.py b/tests/test_api_requestor.py index 2b94d7c98..316ef6fb5 100644 --- a/tests/test_api_requestor.py +++ b/tests/test_api_requestor.py @@ -1264,6 +1264,36 @@ def test_raw_request_with_file_param(self, requestor, http_client_mock): "/v1/invoices/in_123@456", # A backslash does not open an authority: the "/" already closed it. "/v1/\\evil.example", + # Dots are fine anywhere other than a whole "." or ".." segment. + "/v1/reporting/report_types/balance.summary.1", + "/v1/customers/...", + "/v1/customers/.cus_123", + "/v1/customers/cus_123..", + "/v1/customers?email=a..b%40example.com", + # A double-encoded dot reaches the API as the literal "%2E". + "/v1/customers/%252E", + # An encoded slash is fine as long as no piece around it is a dot segment. + "/v1/coupons/summer%2F2017", + ] + + DOT_SEGMENT_PATHS = [ + # HTTP clients remove these segments, so each request would reach a + # different endpoint than the one the path was built for. + "/v1/checkout/sessions/.", + "/v1/checkout/sessions/..", + "/v1/customers/../payment_methods/pm_123", + "/v1/customers/./payment_methods/pm_123", + "/v1/customers/cus_123/sources/..?expand[]=customer", + "/v2/core/accounts/.", + # Some clients decode "%2E" to "." before removing dot segments. + "/v1/checkout/sessions/%2E", + "/v1/checkout/sessions/%2e%2E", + "/v1/checkout/sessions/.%2E", + # A proxy that decodes "%2F" before removing dot segments turns these + # into real path separators. + "/v1/coupons/x%2F..%2F..%2Fcustomers%2Fcus_B", + "/v1/customers/cus_123/sources/..%2F..%2Fcus_B", + "/v1/coupons/..%2fsummer", ] HOSTILE_PATHS = [ @@ -1300,6 +1330,99 @@ def test_request_rejects_hostile_path_without_issuing_request( http_client_mock.assert_no_request() + @pytest.mark.parametrize("path", DOT_SEGMENT_PATHS) + def test_rejects_dot_segment_path(self, path): + with pytest.raises(ValueError): + validate_path(path) + + def test_dot_segment_error_omits_query_string(self): + with pytest.raises(ValueError) as exc_info: + validate_path( + "/v1/payment_intents/..?client_secret=pi_123_secret_456" + ) + + assert "/v1/payment_intents/.." in str(exc_info.value) + assert "pi_123_secret_456" not in str(exc_info.value) + + @pytest.mark.parametrize("path", DOT_SEGMENT_PATHS) + def test_request_rejects_dot_segment_path_without_issuing_request( + self, path, requestor, http_client_mock + ): + with pytest.raises(ValueError): + requestor.request("get", path, base_address="api") + + http_client_mock.assert_no_request() + + @pytest.mark.anyio + @pytest.mark.parametrize("path", DOT_SEGMENT_PATHS) + async def test_request_async_rejects_dot_segment_path_without_issuing_request( + self, path, requestor, http_client_mock + ): + with pytest.raises(ValueError): + await requestor.request_async("get", path, base_address="api") + + http_client_mock.assert_no_request() + + @pytest.mark.parametrize("session_id", [".", ".."]) + def test_service_retrieve_rejects_dot_id_without_issuing_request( + self, session_id, http_client_mock + ): + client = stripe.StripeClient( + "sk_test_123", http_client=http_client_mock.get_mock_http_client() + ) + + with pytest.raises(ValueError): + client.v1.checkout.sessions.retrieve(session_id) + + http_client_mock.assert_no_request() + + @pytest.mark.anyio + @pytest.mark.parametrize("session_id", [".", ".."]) + async def test_service_retrieve_async_rejects_dot_id_without_issuing_request( + self, session_id, http_client_mock + ): + client = stripe.StripeClient( + "sk_test_123", http_client=http_client_mock.get_mock_http_client() + ) + + with pytest.raises(ValueError): + await client.v1.checkout.sessions.retrieve_async(session_id) + + http_client_mock.assert_no_request() + + def test_service_nested_rejects_dot_parent_id_without_issuing_request( + self, http_client_mock + ): + client = stripe.StripeClient( + "sk_test_123", http_client=http_client_mock.get_mock_http_client() + ) + + with pytest.raises(ValueError): + client.v1.customers.payment_methods.retrieve("..", "pm_123") + + http_client_mock.assert_no_request() + + def test_service_rejects_id_with_encoded_dot_segments_without_issuing_request( + self, http_client_mock + ): + client = stripe.StripeClient( + "sk_test_123", http_client=http_client_mock.get_mock_http_client() + ) + + with pytest.raises(ValueError): + client.v1.coupons.retrieve("x/../../customers/cus_B") + + http_client_mock.assert_no_request() + + @pytest.mark.parametrize("session_id", [".", ".."]) + def test_legacy_retrieve_rejects_dot_id_without_issuing_request( + self, session_id, http_client_mock + ): + with pytest.raises(ValueError): + stripe.checkout.Session.retrieve(session_id) + + http_client_mock.assert_no_request() + def test_raw_request_rejects_hostile_path_without_issuing_request( self, http_client_mock ): diff --git a/tests/test_decimal_string.py b/tests/test_decimal_string.py index 8a750a905..0b510dbcb 100644 --- a/tests/test_decimal_string.py +++ b/tests/test_decimal_string.py @@ -7,9 +7,14 @@ - Response hydration: JSON string → Decimal """ +import json from decimal import Decimal -from stripe._encode import _coerce_decimal_string, _coerce_v2_params +from stripe._encode import ( + _coerce_decimal_string, + _coerce_v2_params, + _make_suitable_for_json, +) from stripe._stripe_object import StripeObject @@ -88,6 +93,59 @@ def test_negative(self): assert _coerce_decimal_string("-1.5", encode=False) == Decimal("-1.5") +class TestDecimalStringFixedPoint: + """The API rejects exponent notation, so values are encoded in fixed-point.""" + + def test_small_decimal(self): + assert ( + _coerce_decimal_string(Decimal("0.0000001"), encode=True) + == "0.0000001" + ) + assert ( + _coerce_decimal_string(Decimal("1E-7"), encode=True) == "0.0000001" + ) + assert ( + _coerce_decimal_string(Decimal("-2.5E-7"), encode=True) + == "-0.00000025" + ) + + def test_decimal_with_positive_exponent(self): + assert _coerce_decimal_string(Decimal("1E+3"), encode=True) == "1000" + + def test_small_float(self): + assert _coerce_decimal_string(0.00001, encode=True) == "0.00001" + assert _coerce_decimal_string(-2.5e-7, encode=True) == "-0.00000025" + + def test_large_float(self): + assert _coerce_decimal_string(1e16, encode=True) == "10000000000000000" + assert ( + _coerce_decimal_string(1.5e19, encode=True) + == "15000000000000000000" + ) + + def test_float_keeps_shortest_digits(self): + assert _coerce_decimal_string(0.1, encode=True) == "0.1" + assert ( + _coerce_decimal_string(1e15, encode=True) == "1000000000000000.0" + ) + + def test_non_finite_unchanged(self): + assert _coerce_decimal_string(float("nan"), encode=True) == "nan" + assert _coerce_decimal_string(float("inf"), encode=True) == "inf" + assert _coerce_decimal_string(Decimal("NaN"), encode=True) == "NaN" + + def test_list(self): + assert _coerce_decimal_string( + [Decimal("1E-7"), 1e16], encode=True + ) == ["0.0000001", "10000000000000000"] + + def test_json_request_body(self): + body = json.dumps( + {"price": Decimal("1E-7")}, default=_make_suitable_for_json + ) + assert body == '{"price": "0.0000001"}' + + class TestCoerceV2ParamsDecimalString: """Tests for outbound request coercion (Decimal → str).""" diff --git a/tests/test_encode.py b/tests/test_encode.py index f8f036c8f..5e39339e3 100644 --- a/tests/test_encode.py +++ b/tests/test_encode.py @@ -1,3 +1,4 @@ +import datetime import warnings from stripe._stripe_object import StripeObject @@ -86,6 +87,19 @@ def test_encode_boolean_value(self): result = list(_api_encode({"active": True, "deleted": False})) assert result == [("active", "true"), ("deleted", "false")] + def test_encode_list_with_boolean_values(self): + """Booleans inside a list are encoded as lowercase strings, like top-level booleans.""" + result = list(_api_encode({"flags": [True, False]})) + assert result == [("flags[0]", "true"), ("flags[1]", "false")] + + def test_encode_list_with_datetime_values(self): + """Datetimes inside a list are encoded as unix timestamps, like top-level datetimes.""" + dt = datetime.datetime( + 2024, 1, 2, 3, 4, 5, tzinfo=datetime.timezone.utc + ) + result = list(_api_encode({"created": [dt]})) + assert result == [("created[0]", 1704164645)] + def test_encode_list_value(self): """Test that list values are encoded with indexed keys.""" result = list(_api_encode({"items": ["item1", "item2", "item3"]}))