diff --git a/README.md b/README.md index 7843f12..c82b18d 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,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]); } } @@ -162,6 +163,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 9561442..fb40540 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 $subdomain = null; @@ -19,7 +31,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(); } @@ -108,6 +123,10 @@ protected function validateEnvironmentSettings() } /** + * 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/lib/Checkout/OAuthSdkCredentials.php b/lib/Checkout/OAuthSdkCredentials.php index 0d42179..91f506d 100644 --- a/lib/Checkout/OAuthSdkCredentials.php +++ b/lib/Checkout/OAuthSdkCredentials.php @@ -5,6 +5,7 @@ use DateInterval; use DateTime; use GuzzleHttp\Exception\RequestException; +use Psr\Http\Message\ResponseInterface; class OAuthSdkCredentials implements SdkCredentialsInterface { @@ -127,6 +128,9 @@ private function getAccessToken() } catch (\Throwable $e) { throw new CheckoutException(self::tokenFailureMessage($e)); } + if ($response->getStatusCode() !== 200) { + throw new CheckoutAuthorizationException(self::tokenStatusMessage($response)); + } $body = json_decode((string)$response->getBody(), true); if (!self::isValidTokenResponse($body)) { throw CheckoutAuthorizationException::invalidAccessTokenResponse(); @@ -147,18 +151,27 @@ private function getAccessToken() private static function tokenFailureMessage(\Throwable $failure) { if ($failure instanceof RequestException && $failure->getResponse() !== null) { - $response = $failure->getResponse(); - $message = "OAuth token request failed with status " . $response->getStatusCode(); - $body = json_decode((string)$response->getBody(), true); - $error = is_array($body) ? ($body["error"] ?? null) : null; - if (is_string($error) && in_array($error, self::OAUTH_ERROR_CODES, true)) { - $message .= " (" . $error . ")"; - } - return $message; + return self::tokenStatusMessage($failure->getResponse()); } return "OAuth token request failed: " . CheckoutUtils::describeFailure($failure); } + /** + * @param ResponseInterface $response token response with a status other than 200 + * @return string the status and, when the server sent one, the standard OAuth error code of + * the response. No other text of the response is copied. + */ + private static function tokenStatusMessage(ResponseInterface $response) + { + $message = "OAuth token request failed with status " . $response->getStatusCode(); + $body = json_decode((string)$response->getBody(), true); + $error = is_array($body) ? ($body["error"] ?? null) : null; + if (is_string($error) && in_array($error, self::OAUTH_ERROR_CODES, true)) { + $message .= " (" . $error . ")"; + } + return $message; + } + /** * @param mixed $body decoded token response * @return bool true when it carries a non-empty access_token made of visible ASCII characters diff --git a/test/Checkout/Tests/HttpClientOptionsTest.php b/test/Checkout/Tests/HttpClientOptionsTest.php index 0579079..307d33f 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 0000000..52be9b7 --- /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); + } + } +} diff --git a/test/Checkout/Tests/OAuthTokenStatusTest.php b/test/Checkout/Tests/OAuthTokenStatusTest.php new file mode 100644 index 0000000..f9c545b --- /dev/null +++ b/test/Checkout/Tests/OAuthTokenStatusTest.php @@ -0,0 +1,107 @@ + HandlerStack::create(new MockHandler([ + new Response($statusCode, ['Content-Type' => 'application/json'], $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 errorTokenResponseKeepsItsOAuthErrorCode() + { + try { + $this->initOAuth(400, '{"error":"invalid_client","error_description":"not repeated"}'); + $this->fail('A token response with status 400 was accepted'); + } catch (CheckoutAuthorizationException $e) { + $this->assertSame('OAuth token request failed with status 400 (invalid_client)', $e->getMessage()); + } + } + + /** + * @test + */ + public function okTokenResponseProducesAuthorization() + { + $credentials = $this->initOAuth(200); + + $authorization = $credentials->getAuthorization(AuthorizationType::$oAuth); + + $this->assertSame('Bearer tok', $authorization->getAuthorizationHeader()); + } +}