diff --git a/README.md b/README.md index 1647e4e..a021bbb 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 e1f0ea8..4f921e2 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/lib/Checkout/CheckoutAuthorizationException.php b/lib/Checkout/CheckoutAuthorizationException.php index 260bbf6..d75296e 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/EnvironmentSubdomain.php b/lib/Checkout/EnvironmentSubdomain.php index 649a7b8..371d241 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/lib/Checkout/OAuthSdkCredentials.php b/lib/Checkout/OAuthSdkCredentials.php index 7e8b1b9..7e7a234 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/EnvironmentSubdomainTest.php b/test/Checkout/Tests/EnvironmentSubdomainTest.php new file mode 100644 index 0000000..1a78a4d --- /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() + ); + } +} diff --git a/test/Checkout/Tests/HttpClientOptionsTest.php b/test/Checkout/Tests/HttpClientOptionsTest.php index 0fd8262..71b81ad 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..923f912 --- /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()); + } +}