From 2c7ff9d002a78ba0cef613f4dfe556250c7098cd Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 30 Nov 2026 16:42:03 +0100 Subject: [PATCH 1/3] fix(client): set default timeouts on the sdk http client The HTTP client the SDK creates had no timeout, so a server that accepts the connection and never answers blocked the request forever. That client now uses connect_timeout 10 s and timeout 60 s, and a request over either bound fails with CheckoutApiException (CheckoutException on the OAuth token request). Behaviour change: before, no timeout; now 10 s to connect and 60 s for the whole request. A client passed with httpClientBuilder(), including a DefaultHttpClientBuilder built with your own config, is used as is and does not get these defaults; set connect_timeout and timeout on it to override. --- README.md | 23 ++- lib/Checkout/AbstractCheckoutSdkBuilder.php | 21 ++- test/Checkout/Tests/HttpClientOptionsTest.php | 2 +- .../Checkout/Tests/HttpClientTimeoutsTest.php | 174 ++++++++++++++++++ 4 files changed, 217 insertions(+), 3 deletions(-) create mode 100644 test/Checkout/Tests/HttpClientTimeoutsTest.php diff --git a/README.md b/README.md index 1647e4ee..a021bbb5 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,8 @@ class CustomCaHttpClientBuilder implements HttpClientBuilderInterface { public function getClient() { - return new Client(['verify' => '/path/to/ca-bundle.pem']); + // A client you pass gets no default timeouts, so set them too (see HTTP timeouts below). + return new Client(['verify' => '/path/to/ca-bundle.pem', 'connect_timeout' => 10, 'timeout' => 60]); } } @@ -171,6 +172,26 @@ $checkoutApi = CheckoutSdk::builder()->staticKeys() A `cURL error 60` means PHP cannot find a CA bundle that trusts the API certificate; fix the CA configuration rather than turning verification off. +### HTTP timeouts + +The HTTP client the SDK creates waits up to 10 seconds to connect (`connect_timeout`) and up to 60 seconds for the whole request (`timeout`), sending and receiving the body included, so a large upload or report download on a slow connection needs a client with a longer `timeout`. These bounds hold with Guzzle's cURL handler, which Guzzle uses when the PHP cURL extension is installed; without it, Guzzle's stream handler ignores `connect_timeout` and applies `timeout` to each read instead of the whole request. An API request that exceeds either bound throws a `CheckoutApiException`. With OAuth, a token request that exceeds them throws a `CheckoutException`, both the first one, sent while the SDK is built, and a renewal requested before an API request. + +A client passed with `httpClientBuilder()` is used as is and does not get these defaults, so set the bounds you need on it: + +```php +use Checkout\DefaultHttpClientBuilder; + +$checkoutApi = CheckoutSdk::builder()->staticKeys() + ->secretKey("secret_key") + ->environment(Environment::sandbox()) + ->environmentSubdomain("subdomain") + ->httpClientBuilder(new DefaultHttpClientBuilder([ + 'connect_timeout' => 5, + 'timeout' => 30, + ])) + ->build(); +``` + ## Exception handling All the API responses that do not fall in the 2** status codes, the SDK will throw a `CheckoutApiException`. diff --git a/lib/Checkout/AbstractCheckoutSdkBuilder.php b/lib/Checkout/AbstractCheckoutSdkBuilder.php index e1f0ea8b..4f921e22 100644 --- a/lib/Checkout/AbstractCheckoutSdkBuilder.php +++ b/lib/Checkout/AbstractCheckoutSdkBuilder.php @@ -8,6 +8,18 @@ abstract class AbstractCheckoutSdkBuilder { + /** + * Seconds the HTTP client created by the SDK waits to connect to the server. + * Guzzle's stream handler (no cURL extension) ignores it. + */ + const DEFAULT_CONNECT_TIMEOUT_SECONDS = 10; + + /** + * Seconds the HTTP client created by the SDK waits for a whole request, connection + * included, before it fails. + * With Guzzle's stream handler (no cURL extension) it bounds each read instead. + */ + const DEFAULT_TIMEOUT_SECONDS = 60; protected $environment; protected $environmentSubdomain = null; @@ -17,7 +29,10 @@ abstract class AbstractCheckoutSdkBuilder public function __construct() { $this->environment = Environment::sandbox(); - $this->httpClientBuilder = new DefaultHttpClientBuilder([]); + $this->httpClientBuilder = new DefaultHttpClientBuilder([ + 'connect_timeout' => self::DEFAULT_CONNECT_TIMEOUT_SECONDS, + 'timeout' => self::DEFAULT_TIMEOUT_SECONDS, + ]); $this->setDefaultLogger(); } @@ -42,6 +57,10 @@ public function environmentSubdomain($subdomain) } /** + * Replaces the HTTP client the SDK creates. The client returned by the given builder is + * used as is: the SDK default timeouts are not applied to it, so set connect_timeout and + * timeout on it yourself. + * * @param HttpClientBuilderInterface $httpClientBuilder * @return $this */ diff --git a/test/Checkout/Tests/HttpClientOptionsTest.php b/test/Checkout/Tests/HttpClientOptionsTest.php index 0fd82625..71b81ad7 100644 --- a/test/Checkout/Tests/HttpClientOptionsTest.php +++ b/test/Checkout/Tests/HttpClientOptionsTest.php @@ -22,7 +22,7 @@ use Monolog\Logger; /** - * The SDK must leave transport options to the HTTP client: requests use Guzzle's defaults + * The SDK must leave TLS options to the HTTP client: requests use Guzzle's TLS defaults * unless the caller configures the client through a custom HttpClientBuilderInterface. */ class HttpClientOptionsTest extends MockeryTestCase diff --git a/test/Checkout/Tests/HttpClientTimeoutsTest.php b/test/Checkout/Tests/HttpClientTimeoutsTest.php new file mode 100644 index 00000000..52be9b75 --- /dev/null +++ b/test/Checkout/Tests/HttpClientTimeoutsTest.php @@ -0,0 +1,174 @@ +setAccessible(true); + return $property->getValue($sdkBuilder)->getClient(); + } + + /** + * Opens a local TCP server that completes the connection and never sends a byte back. + * + * @return resource + */ + private static function openSilentServer() + { + $server = stream_socket_server('tcp://127.0.0.1:0', $errorNumber, $errorMessage); + if ($server === false) { + self::fail('Cannot open a local server: ' . $errorMessage); + } + return $server; + } + + /** + * @param resource $server + * @return string + */ + private static function urlOf($server) + { + return 'http://' . stream_socket_get_name($server, false) . '/'; + } + + /** + * @return DefaultHttpClientBuilder + */ + private static function shortTimeoutBuilder() + { + return new DefaultHttpClientBuilder([ + 'connect_timeout' => self::SHORT_TIMEOUT_SECONDS, + 'timeout' => self::SHORT_TIMEOUT_SECONDS, + ]); + } + + /** + * @test + */ + public function sdkCreatedClientHasDefaultTimeouts() + { + $this->assertSame(10, AbstractCheckoutSdkBuilder::DEFAULT_CONNECT_TIMEOUT_SECONDS); + $this->assertSame(60, AbstractCheckoutSdkBuilder::DEFAULT_TIMEOUT_SECONDS); + + $sdkBuilders = [ + CheckoutSdk::builder()->staticKeys(), + CheckoutSdk::builder()->oAuth(), + CheckoutSdk::builder()->previous()->staticKeys(), + ]; + foreach ($sdkBuilders as $sdkBuilder) { + $client = self::clientOf($sdkBuilder); + $this->assertSame(10, $client->getConfig('connect_timeout')); + $this->assertSame(60, $client->getConfig('timeout')); + } + } + + /** + * @test + */ + public function customClientKeepsItsOwnOptions() + { + $withTimeout = new DefaultHttpClientBuilder(['timeout' => 5]); + $withoutTimeouts = new DefaultHttpClientBuilder([]); + + $sdkBuilder = CheckoutSdk::builder()->staticKeys()->httpClientBuilder($withTimeout); + $client = self::clientOf($sdkBuilder); + $this->assertSame($withTimeout->getClient(), $client); + $this->assertSame(5, $client->getConfig('timeout')); + $this->assertNull($client->getConfig('connect_timeout')); + + $sdkBuilder = CheckoutSdk::builder()->oAuth()->httpClientBuilder($withoutTimeouts); + $client = self::clientOf($sdkBuilder); + $this->assertSame($withoutTimeouts->getClient(), $client); + $this->assertNull($client->getConfig('timeout')); + $this->assertNull($client->getConfig('connect_timeout')); + } + + /** + * @test + */ + public function apiRequestToServerThatNeverAnswersFailsWithApiException() + { + $server = self::openSilentServer(); + $logger = new Logger('checkout-sdk-test-php'); + $logger->pushHandler(new NullHandler()); + $apiClient = new ApiClient(new CheckoutConfiguration( + $this->createMock(SdkCredentialsInterface::class), + Environment::sandbox(), + self::shortTimeoutBuilder(), + $logger + ), self::urlOf($server)); + + $start = microtime(true); + try { + $apiClient->get('payments/pay_123', new SdkAuthorization(PlatformType::$default, 'sk_test_xxx')); + $this->fail('The request to a server that never answers did not fail'); + } catch (CheckoutApiException $e) { + $this->assertLessThan(self::MAX_ELAPSED_SECONDS, microtime(true) - $start); + } finally { + fclose($server); + } + } + + /** + * @test + */ + public function tokenRequestToServerThatNeverAnswersFailsWithCheckoutException() + { + $server = self::openSilentServer(); + + $start = microtime(true); + try { + OAuthSdkCredentials::init( + self::shortTimeoutBuilder(), + 'client_id', + 'secret_marker_5f2c', + self::urlOf($server) . 'connect/token', + ['gateway'] + ); + $this->fail('The token request to a server that never answers did not fail'); + } catch (CheckoutException $e) { + $this->assertLessThan(self::MAX_ELAPSED_SECONDS, microtime(true) - $start); + $this->assertFalse(strpos($e->getMessage(), 'secret_marker_5f2c') !== false); + } finally { + fclose($server); + } + } +} From ee705f51e92e3d7bbc871830797120b8b12566b4 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 30 Nov 2026 16:44:03 +0100 Subject: [PATCH 2/3] fix(client): reject a token response other than 200 The token response was only checked for its body, so a response with a status other than 200, the success status of a token response, was accepted when its body was valid: any status when the HTTP client does not throw on error statuses (http_errors set to false), and with any client the 1xx, 3xx and 2xx other than 200 statuses Guzzle does not throw on. Such a response now throws CheckoutAuthorizationException with the message "OAuth token request failed with status ", through the new CheckoutAuthorizationException::tokenRequestFailed() factory. --- .../CheckoutAuthorizationException.php | 9 ++ lib/Checkout/OAuthSdkCredentials.php | 4 + test/Checkout/Tests/OAuthTokenStatusTest.php | 93 +++++++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 test/Checkout/Tests/OAuthTokenStatusTest.php diff --git a/lib/Checkout/CheckoutAuthorizationException.php b/lib/Checkout/CheckoutAuthorizationException.php index 260bbf6a..d75296e0 100644 --- a/lib/Checkout/CheckoutAuthorizationException.php +++ b/lib/Checkout/CheckoutAuthorizationException.php @@ -40,6 +40,15 @@ public static function invalidAccessTokenResponse() ); } + /** + * @param int $statusCode HTTP status code of the token response + * @return CheckoutAuthorizationException + */ + public static function tokenRequestFailed($statusCode) + { + return new CheckoutAuthorizationException("OAuth token request failed with status " . $statusCode); + } + /** * @param $keyType * @return CheckoutAuthorizationException diff --git a/lib/Checkout/OAuthSdkCredentials.php b/lib/Checkout/OAuthSdkCredentials.php index 7e8b1b9d..7e7a2341 100644 --- a/lib/Checkout/OAuthSdkCredentials.php +++ b/lib/Checkout/OAuthSdkCredentials.php @@ -111,6 +111,10 @@ private function getAccessToken() } catch (Exception $e) { throw new CheckoutException($e->getMessage()); } + $statusCode = $response->getStatusCode(); + if ($statusCode !== 200) { + throw CheckoutAuthorizationException::tokenRequestFailed($statusCode); + } $body = json_decode((string)$response->getBody(), true); if (!self::isValidTokenResponse($body)) { throw CheckoutAuthorizationException::invalidAccessTokenResponse(); diff --git a/test/Checkout/Tests/OAuthTokenStatusTest.php b/test/Checkout/Tests/OAuthTokenStatusTest.php new file mode 100644 index 00000000..923f9126 --- /dev/null +++ b/test/Checkout/Tests/OAuthTokenStatusTest.php @@ -0,0 +1,93 @@ + HandlerStack::create(new MockHandler([ + new Response($statusCode, ['Content-Type' => 'application/json'], self::VALID_TOKEN_BODY), + ])), + 'http_errors' => false, + ]); + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method('getClient')->willReturn($client); + return OAuthSdkCredentials::init( + $builder, + 'client_id', + 'client_secret', + 'https://access.sandbox.checkout.com/connect/token', + ['gateway'] + ); + } + + /** + * @return array + */ + public static function nonSuccessStatusCodes() + { + return [ + '199' => [199], + '201' => [201], + '299' => [299], + '302' => [302], + '400' => [400], + '401' => [401], + '403' => [403], + '500' => [500], + '503' => [503], + ]; + } + + /** + * @test + * @dataProvider nonSuccessStatusCodes + * @param int $statusCode + */ + public function nonSuccessTokenResponseIsRejectedWithItsStatus($statusCode) + { + try { + $this->initOAuth($statusCode); + $this->fail('A token response with status ' . $statusCode . ' was accepted'); + } catch (CheckoutAuthorizationException $e) { + $this->assertSame('OAuth token request failed with status ' . $statusCode, $e->getMessage()); + } + } + + /** + * @test + */ + public function okTokenResponseProducesAuthorization() + { + $credentials = $this->initOAuth(200); + + $authorization = $credentials->getAuthorization(AuthorizationType::$oAuth); + + $this->assertSame('Bearer tok', $authorization->getAuthorizationHeader()); + } +} From 8d9274de4c651e06cef457cdcd4044aace9df78a Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 30 Nov 2026 16:49:00 +0100 Subject: [PATCH 3/3] fix(client): do not accept a subdomain with a trailing newline The subdomain pattern ended with $, which also matches before a final newline, so a value such as one read from a file with its line ending was accepted and placed in the request host. With the D modifier such a value is not used as a subdomain and the default hosts apply, as for any other value outside the pattern. --- lib/Checkout/EnvironmentSubdomain.php | 4 +- .../Tests/EnvironmentSubdomainTest.php | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 test/Checkout/Tests/EnvironmentSubdomainTest.php diff --git a/lib/Checkout/EnvironmentSubdomain.php b/lib/Checkout/EnvironmentSubdomain.php index 649a7b8f..371d2419 100644 --- a/lib/Checkout/EnvironmentSubdomain.php +++ b/lib/Checkout/EnvironmentSubdomain.php @@ -30,7 +30,9 @@ private function createUrlWithSubdomain($originalUrl, $subdomain) { $newEnvironment = $originalUrl; - $regex = '/^[0-9a-z]+$/'; + // The D modifier anchors $ to the very end of the subject, so a value with a trailing + // newline is not accepted as a subdomain. + $regex = '/^[0-9a-z]+$/D'; if (preg_match($regex, $subdomain)) { $urlParts = parse_url($originalUrl); $newHost = $subdomain . '.' . $urlParts['host']; diff --git a/test/Checkout/Tests/EnvironmentSubdomainTest.php b/test/Checkout/Tests/EnvironmentSubdomainTest.php new file mode 100644 index 00000000..1a78a4d5 --- /dev/null +++ b/test/Checkout/Tests/EnvironmentSubdomainTest.php @@ -0,0 +1,38 @@ +assertSame("https://abc.api.sandbox.checkout.com/", $environmentSubdomain->getBaseUri()); + $this->assertSame( + "https://abc.access.sandbox.checkout.com/connect/token", + $environmentSubdomain->getAuthorizationUri() + ); + } + + /** + * @test + */ + public function subdomainWithTrailingNewlineIsNotUsed() + { + $environmentSubdomain = new EnvironmentSubdomain(Environment::sandbox(), "abc\n"); + + $this->assertSame("https://api.sandbox.checkout.com/", $environmentSubdomain->getBaseUri()); + $this->assertSame( + "https://access.sandbox.checkout.com/connect/token", + $environmentSubdomain->getAuthorizationUri() + ); + } +}