From 211496fc20bd021c4e23b1eea81b64825b2673bb Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 30 Nov 2026 16:42:13 +0100 Subject: [PATCH 1/2] fix(client): add default timeouts to the sdk http session The session the SDK creates when no http_client_builder is set had no timeout, and requests waits forever by default, so a stalled connection blocked the caller indefinitely. Behaviour change: requests made through the SDK-created session now use a 10 second connect timeout and a 60 second read timeout, unless a timeout is passed for the call. A session returned by a custom http_client_builder is used as is; the README shows how to set bounds on it. --- README.md | 42 ++++++++++++- checkout_sdk/default_http_client.py | 37 ++++++++++- tests/default_http_client_test.py | 96 +++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 tests/default_http_client_test.py diff --git a/README.md b/README.md index 69c4b293..992ac315 100644 --- a/README.md +++ b/README.md @@ -155,11 +155,11 @@ logging.getLogger('checkout').setLevel(logging.INFO) Checkout SDK uses `requests` library to perform http operations, and you can provide your own custom http client implementing `HttpClientBuilderInterface` ```python -import requests from requests import Session import checkout_sdk from checkout_sdk.checkout_sdk import CheckoutSdk +from checkout_sdk.default_http_client import DefaultTimeoutSession from checkout_sdk.environment import Environment from checkout_sdk.oauth_scopes import OAuthScopes from checkout_sdk.http_client_interface import HttpClientBuilderInterface @@ -168,7 +168,7 @@ from checkout_sdk.http_client_interface import HttpClientBuilderInterface class CustomHttpClientBuilder(HttpClientBuilderInterface): def get_client(self) -> Session: - session = requests.Session() + session = DefaultTimeoutSession() # keeps the SDK default timeouts, see Timeouts below session.max_redirects = 5 return session @@ -188,6 +188,44 @@ def oauth(): payments_client.refund_payment('payment_id') ``` +### Timeouts + +The session the SDK creates by default gives every request a timeout of 10 seconds to connect and send the request +(each wait on the socket, so a large upload is not limited as a whole) and 60 seconds between bytes of the response, +not a limit on the whole request (`DEFAULT_CONNECT_TIMEOUT` and `DEFAULT_READ_TIMEOUT` in +`checkout_sdk.default_http_client`). The 10 seconds start once the host name is resolved: the DNS lookup is not +included and keeps the limits of the system resolver. + +A session returned by your own `HttpClientBuilderInterface` is used as is, so the SDK adds no timeout to it. `requests` +waits forever unless a timeout is given, so set your own bounds on the session you provide. To keep the defaults above, +return a `DefaultTimeoutSession`, as in the example above. To use other bounds, mount an adapter that sets them on every +request that passes no timeout of its own: + +```python +from requests import Session +from requests.adapters import HTTPAdapter + +from checkout_sdk.http_client_interface import HttpClientBuilderInterface + + +class TimeoutAdapter(HTTPAdapter): + + def send(self, request, **kwargs): + if kwargs.get('timeout') is None: + kwargs['timeout'] = (5, 30) # (connect, read) in seconds + return super().send(request, **kwargs) + + +class TimeoutHttpClientBuilder(HttpClientBuilderInterface): + + def get_client(self) -> Session: + session = Session() + session.mount('https://', TimeoutAdapter()) + return session +``` + +Pass it to the builder with `.http_client_builder(TimeoutHttpClientBuilder())`, as in the example above. + ## Exception handling All the API responses that do not fall in the 2** status codes will cause a `CheckoutApiException`. The exception encapsulates diff --git a/checkout_sdk/default_http_client.py b/checkout_sdk/default_http_client.py index 2f9f9d59..06a10747 100644 --- a/checkout_sdk/default_http_client.py +++ b/checkout_sdk/default_http_client.py @@ -4,11 +4,46 @@ from checkout_sdk.http_client_interface import HttpClientBuilderInterface +# Seconds to wait for the connection to the API host to be established. +DEFAULT_CONNECT_TIMEOUT = 10 +# Seconds to wait between bytes of the response once the request has been sent. +DEFAULT_READ_TIMEOUT = 60 + + +class DefaultTimeoutSession(requests.Session): + """ + Session created by the SDK when no http_client_builder is provided. requests has no + session-wide timeout and waits forever by default, so every request made through this + session is bounded by DEFAULT_CONNECT_TIMEOUT and DEFAULT_READ_TIMEOUT unless the call + passes its own timeout. + """ + + # Index of timeout in the positional arguments of requests.Session.request after method and url + # (params, data, headers, cookies, files, auth, timeout). + _TIMEOUT_POSITION = 6 + + def request(self, method, url, *args, **kwargs): + """ + Sends the request with the default (connect, read) timeout unless the call passes its own. + + Args: + method: the HTTP method. + url: the URL of the request. + *args: the other positional arguments of requests.Session.request. + **kwargs: the other keyword arguments of requests.Session.request. + + Returns: + requests.Response: the response. + """ + if len(args) <= self._TIMEOUT_POSITION: + kwargs.setdefault('timeout', (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT)) + return super().request(method, url, *args, **kwargs) + class DefaultHttpClientBuilder(HttpClientBuilderInterface): def __init__(self): - self.session = requests.Session() + self.session = DefaultTimeoutSession() def get_client(self): return self.session diff --git a/tests/default_http_client_test.py b/tests/default_http_client_test.py new file mode 100644 index 00000000..777e52a8 --- /dev/null +++ b/tests/default_http_client_test.py @@ -0,0 +1,96 @@ +import json + +from requests import Response, Session +from requests.adapters import HTTPAdapter + +from checkout_sdk.checkout_sdk import CheckoutSdk +from checkout_sdk.default_http_client import DefaultHttpClientBuilder, DefaultTimeoutSession, \ + DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT +from checkout_sdk.http_client_interface import HttpClientBuilderInterface + + +def ok_response(request): + response = Response() + response.status_code = 200 + response.request = request + response.url = request.url + response.headers['Content-Type'] = 'application/json' + response._content = json.dumps({'id': 'pay_123'}).encode('utf-8') + return response + + +def stub_transport(mocker): + # Only the transport is stubbed: the session merges its settings into the request, so the + # test sees the timeout the socket would get. + return mocker.patch.object(HTTPAdapter, 'send', autospec=True, + side_effect=lambda adapter, request, **kwargs: ok_response(request)) + + +class CustomHttpClientBuilder(HttpClientBuilderInterface): + + def __init__(self): + self.session = Session() + + def get_client(self) -> Session: + return self.session + + +def sdk_builder(): + return CheckoutSdk.builder() \ + .secret_key('sk_sbox_m73dzbpy7cf3gfd46xr4yj5xo4e') \ + .environment_subdomain('123domain') + + +def test_default_timeouts_are_10_seconds_to_connect_and_60_seconds_to_read(): + assert DEFAULT_CONNECT_TIMEOUT == 10 + assert DEFAULT_READ_TIMEOUT == 60 + + +def test_should_apply_the_default_timeouts_to_every_request_of_the_default_session(mocker): + send = stub_transport(mocker) + session = DefaultHttpClientBuilder().get_client() + + session.request(method='POST', url='https://api.sandbox.checkout.com/payments') + session.get('https://api.sandbox.checkout.com/payments/pay_123') + + assert isinstance(session, DefaultTimeoutSession) + assert [call.kwargs['timeout'] for call in send.call_args_list] == [ + (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT), (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT)] + + +def test_should_keep_a_timeout_passed_to_the_request_of_the_default_session(mocker): + send = stub_transport(mocker) + + DefaultHttpClientBuilder().get_client().request(method='GET', url='https://api.sandbox.checkout.com/', + timeout=5) + + assert send.call_args.kwargs['timeout'] == 5 + + +def test_should_keep_a_timeout_passed_by_position_to_the_request_of_the_default_session(mocker): + send = stub_transport(mocker) + + DefaultTimeoutSession().request('GET', 'https://example.com/', None, None, None, None, None, None, 7) + + assert send.call_args.kwargs['timeout'] == 7 + + +def test_should_send_sdk_requests_with_the_default_timeouts_when_no_http_client_builder_is_set(mocker): + send = stub_transport(mocker) + + sdk_builder().build().payments.get_payment_details('pay_123') + + assert send.call_count == 1 + assert send.call_args.kwargs['timeout'] == (DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT) + + +def test_should_leave_the_session_of_a_custom_http_client_builder_untouched(mocker): + send = stub_transport(mocker) + http_client_builder = CustomHttpClientBuilder() + + sdk = sdk_builder().http_client_builder(http_client_builder).build() + sdk.payments.get_payment_details('pay_123') + + assert type(http_client_builder.session) is Session + assert send.call_count == 1 + assert send.call_args.kwargs['timeout'] is None From b280753c8d1fb26b84b46278b2e966c8802b80fe Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 30 Nov 2026 16:48:03 +0100 Subject: [PATCH 2/2] fix(client): raise an sdk exception when the token request times out With the default timeouts a stalled token request now ends in a read timeout. That error is not a ConnectionError, so the raw requests exception reached the caller instead of an SDK exception. The token request now raises CheckoutAuthorizationException("OAuth token request timed out") for a read timeout, chained to the original error, with a fixed message like the other token errors. A connect timeout is a ConnectionError and keeps its message. API requests that time out keep raising CheckoutException, now covered by a test against a server that never answers. Behaviour change, also with a session from http_client_builder that sets its own timeout: a token request read timeout used to reach the caller as requests ReadTimeout and is now CheckoutAuthorizationException. --- README.md | 3 ++- checkout_sdk/oauth_credentials.py | 19 +++++++++++++- tests/api_client_timeout_test.py | 31 +++++++++++++++++++++++ tests/checkout_test_utils.py | 41 +++++++++++++++++++++++++++++++ tests/oauth_credentials_test.py | 38 ++++++++++++++++++++++++++++ 5 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 tests/api_client_timeout_test.py diff --git a/README.md b/README.md index 992ac315..751fc772 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,8 @@ The session the SDK creates by default gives every request a timeout of 10 secon (each wait on the socket, so a large upload is not limited as a whole) and 60 seconds between bytes of the response, not a limit on the whole request (`DEFAULT_CONNECT_TIMEOUT` and `DEFAULT_READ_TIMEOUT` in `checkout_sdk.default_http_client`). The 10 seconds start once the host name is resolved: the DNS lookup is not -included and keeps the limits of the system resolver. +included and keeps the limits of the system resolver. A request that times out raises a `CheckoutException`, or a +`CheckoutAuthorizationException` for the OAuth token request. A session returned by your own `HttpClientBuilderInterface` is used as is, so the SDK adds no timeout to it. `requests` waits forever unless a timeout is given, so set your own bounds on the session you provide. To keep the defaults above, diff --git a/checkout_sdk/oauth_credentials.py b/checkout_sdk/oauth_credentials.py index ae610411..00eee66a 100644 --- a/checkout_sdk/oauth_credentials.py +++ b/checkout_sdk/oauth_credentials.py @@ -4,7 +4,7 @@ from abc import ABCMeta from datetime import datetime, timedelta -from requests import HTTPError, Session, ConnectionError +from requests import HTTPError, Session, ConnectionError, Timeout from checkout_sdk.authorization_type import AuthorizationType from checkout_sdk.environment import Environment @@ -58,6 +58,18 @@ def get_authorization(self, authorization_type: AuthorizationType): raise CheckoutAuthorizationException.invalid_authorization(authorization_type=authorization_type) def get_access_token(self): + """ + Returns the cached access token while it is valid, otherwise requests a new one. + + Returns: + OAuthAccessToken: the access token. + + Raises: + CheckoutAuthorizationException: if the token endpoint answers with an error status, the connection + cannot be established, or the request times out while waiting for the response. A response body + that stops arriving is reported by requests as a connection error, so it raises the "Unable to + establish connection" message even though the connection was made. + """ if self.__access_token is not None and self.__access_token.is_valid(): return self.__access_token @@ -82,8 +94,13 @@ def get_access_token(self): err.response.status_code) raise CheckoutAuthorizationException(message) from err except ConnectionError as err: + # A connect timeout is a ConnectionError too and keeps this message, and so is a read timeout while + # requests reads the response body (it raises ConnectionError there), even though the connection was made. raise CheckoutAuthorizationException( 'Unable to establish connection to host: ({})'.format(self.__authorization_uri)) from err + except Timeout as err: + # A read timeout: a fixed message, like the other token errors. + raise CheckoutAuthorizationException('OAuth token request timed out') from err response_json = response.json() self.__access_token = OAuthAccessToken(token=response_json['access_token'], diff --git a/tests/api_client_timeout_test.py b/tests/api_client_timeout_test.py new file mode 100644 index 00000000..a66911ff --- /dev/null +++ b/tests/api_client_timeout_test.py @@ -0,0 +1,31 @@ +import time + +import pytest +from requests.exceptions import Timeout + +from checkout_sdk import default_http_client +from checkout_sdk.api_client import ApiClient +from checkout_sdk.checkout_configuration import CheckoutConfiguration +from checkout_sdk.default_http_client import DefaultHttpClientBuilder +from checkout_sdk.environment import Environment +from checkout_sdk.exception import CheckoutException +from checkout_sdk.platform_type import PlatformType +from checkout_sdk.sdk_authorization import SdkAuthorization +from tests.checkout_test_utils import unresponsive_server + + +def test_should_raise_a_checkout_exception_when_the_api_does_not_answer_in_time(monkeypatch): + # The real default session against a server that never answers, with a short read bound. + monkeypatch.setattr(default_http_client, 'DEFAULT_READ_TIMEOUT', 0.5) + configuration = CheckoutConfiguration(None, Environment.sandbox(), DefaultHttpClientBuilder().get_client()) + + with unresponsive_server() as base_uri: + api_client = ApiClient(configuration, base_uri + '/') + started = time.monotonic() + with pytest.raises(CheckoutException) as excinfo: + api_client.get('payments/pay_123', SdkAuthorization(PlatformType.DEFAULT, 'sk_test')) + elapsed = time.monotonic() - started + + assert type(excinfo.value) is CheckoutException + assert isinstance(excinfo.value.__cause__, Timeout) + assert elapsed < 5 diff --git a/tests/checkout_test_utils.py b/tests/checkout_test_utils.py index 1dc6344d..e2100624 100644 --- a/tests/checkout_test_utils.py +++ b/tests/checkout_test_utils.py @@ -1,8 +1,11 @@ from __future__ import absolute_import import logging +import socket +import threading import time import uuid +from contextlib import contextmanager from pathlib import Path from checkout_sdk.common.common import Address, Phone, CustomerRequest, AccountHolder @@ -142,3 +145,41 @@ def get_payment_recipient(): recipient.zip = '12345' recipient.country = Country.ES return recipient + + +@contextmanager +def unresponsive_server(close_after=5): + """ + Local server that accepts connections and never answers. Yields its base URL. Each connection is closed + close_after seconds after it is accepted, so a client with no timeout fails instead of hanging the test. + """ + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.bind(('127.0.0.1', 0)) + server.listen(5) + server.settimeout(0.1) + connections = [] + stopped = threading.Event() + + def accept(): + while not stopped.is_set(): + try: + connection = server.accept()[0] + connections.append(connection) + closer = threading.Timer(close_after, connection.close) + closer.daemon = True + closer.start() + except socket.timeout: + continue + except OSError: + return + + acceptor = threading.Thread(target=accept, daemon=True) + acceptor.start() + try: + yield 'http://127.0.0.1:{}'.format(server.getsockname()[1]) + finally: + stopped.set() + acceptor.join() # no accept can happen after this, so the loop below closes every connection + server.close() + for connection in connections: + connection.close() diff --git a/tests/oauth_credentials_test.py b/tests/oauth_credentials_test.py index 0c190a53..fee3c59f 100644 --- a/tests/oauth_credentials_test.py +++ b/tests/oauth_credentials_test.py @@ -1,11 +1,17 @@ import json +import time import pytest from requests import Response, Session from requests.adapters import HTTPAdapter +from requests.exceptions import ConnectTimeout, Timeout +from checkout_sdk import default_http_client +from checkout_sdk.default_http_client import DefaultHttpClientBuilder from checkout_sdk.environment import Environment +from checkout_sdk.exception import CheckoutAuthorizationException from checkout_sdk.oauth_credentials import OAuthSdkCredentials +from tests.checkout_test_utils import unresponsive_server def token_response(request): @@ -56,3 +62,35 @@ def test_should_use_the_ca_bundle_configured_on_the_http_client(self, mocker): send = self.request_token(mocker, http_client) assert send.call_args.kwargs['verify'] == '/path/to/ca-bundle.pem' + + def test_should_raise_a_checkout_authorization_exception_when_the_token_request_times_out(self, monkeypatch): + # The real default session against a server that never answers, with a short read bound. + monkeypatch.setattr(default_http_client, 'DEFAULT_READ_TIMEOUT', 0.5) + + with unresponsive_server() as base_uri: + authorization_uri = base_uri + '/connect/token' + credentials = OAuthSdkCredentials(DefaultHttpClientBuilder().get_client(), Environment.sandbox(), + 'client_id', 'client_secret', authorization_uri, ['vault']) + started = time.monotonic() + with pytest.raises(CheckoutAuthorizationException) as excinfo: + credentials.get_access_token() + elapsed = time.monotonic() - started + + assert str(excinfo.value) == 'OAuth token request timed out' + assert 'client_secret' not in str(excinfo.value) + assert 'Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=' not in str(excinfo.value) # base64 of the basic auth value + assert isinstance(excinfo.value.__cause__, Timeout) + assert elapsed < 5 + + def test_should_keep_the_connection_message_when_the_token_request_cannot_connect_in_time(self, mocker): + http_client = Session() + mocker.patch.object(http_client, 'request', side_effect=ConnectTimeout('connect timed out')) + credentials = OAuthSdkCredentials(http_client, Environment.sandbox(), 'client_id', 'client_secret', + 'https://access.sandbox.checkout.com/connect/token', ['vault']) + + with pytest.raises(CheckoutAuthorizationException) as excinfo: + credentials.get_access_token() + + assert str(excinfo.value) == \ + 'Unable to establish connection to host: (https://access.sandbox.checkout.com/connect/token)' + assert isinstance(excinfo.value.__cause__, ConnectTimeout)