From 030ccbfe82a2e97e6f96bfbec84274cda2f24a56 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Thu, 3 Dec 2026 11:12:45 +0100 Subject: [PATCH 1/4] fix(client): security hardening Backport the security hardening of the main line to the 3.2.x line: input validation of request headers and improved error handling of the API client, the OAuth token request and CheckoutApiException. The test script passes the container only the variables the workflows set. --- .github/scripts/phpunit-in-docker.sh | 25 +- README.md | 2 +- .../AbstractStaticKeysCheckoutSdkBuilder.php | 35 +- .../AbstractStaticKeysSdkCredentials.php | 7 +- lib/Checkout/ApiClient.php | 190 +- lib/Checkout/CheckoutApi.php | 33 +- lib/Checkout/CheckoutApiException.php | 89 +- .../CheckoutAuthorizationException.php | 14 +- lib/Checkout/CheckoutConfiguration.php | 1 + lib/Checkout/CheckoutOAuthSdkBuilder.php | 1 + lib/Checkout/CheckoutStaticKeysSdkBuilder.php | 6 +- lib/Checkout/CheckoutUtils.php | 145 ++ lib/Checkout/Issuing/IssuingClient.php | 14 +- lib/Checkout/OAuthAccessToken.php | 7 +- lib/Checkout/OAuthSdkCredentials.php | 64 +- lib/Checkout/Previous/CheckoutApi.php | 15 +- .../CheckoutStaticKeysPreviousSdkBuilder.php | 6 +- .../PreviousStaticKeysSdkCredentials.php | 7 +- lib/Checkout/SdkAuthorization.php | 45 +- .../Sessions/SessionSecretSdkCredentials.php | 9 +- lib/Checkout/Sessions/SessionsClient.php | 38 +- lib/Checkout/StaticKeysSdkCredentials.php | 7 +- .../Webhooks/Previous/WebhooksClient.php | 21 +- lib/Checkout/Workflows/WorkflowsClient.php | 28 +- .../ErrorHandlingFailingContextException.php | 14 + .../Tests/ErrorHandlingForeignException.php | 12 + .../ErrorHandlingObjectContextException.php | 14 + .../Tests/ErrorHandlingOtherCodeException.php | 19 + .../Tests/ErrorHandlingStringableKey.php | 29 + test/Checkout/Tests/ErrorHandlingTest.php | 1696 +++++++++++++++++ .../Tests/ErrorHandlingTextCodeException.php | 18 + .../Tests/ErrorHandlingThrowingText.php | 14 + .../Tests/ErrorHandlingUnreadableIterator.php | 15 + test/Checkout/Tests/OAuthIntegrationTest.php | 7 +- test/Checkout/Tests/SandboxTestFixture.php | 5 +- 35 files changed, 2494 insertions(+), 158 deletions(-) create mode 100644 test/Checkout/Tests/ErrorHandlingFailingContextException.php create mode 100644 test/Checkout/Tests/ErrorHandlingForeignException.php create mode 100644 test/Checkout/Tests/ErrorHandlingObjectContextException.php create mode 100644 test/Checkout/Tests/ErrorHandlingOtherCodeException.php create mode 100644 test/Checkout/Tests/ErrorHandlingStringableKey.php create mode 100644 test/Checkout/Tests/ErrorHandlingTest.php create mode 100644 test/Checkout/Tests/ErrorHandlingTextCodeException.php create mode 100644 test/Checkout/Tests/ErrorHandlingThrowingText.php create mode 100644 test/Checkout/Tests/ErrorHandlingUnreadableIterator.php diff --git a/.github/scripts/phpunit-in-docker.sh b/.github/scripts/phpunit-in-docker.sh index 0f364007..dd16c72a 100755 --- a/.github/scripts/phpunit-in-docker.sh +++ b/.github/scripts/phpunit-in-docker.sh @@ -33,13 +33,30 @@ docker run --rm -u "$(id -u):$(id -g)" -e COMPOSER_HOME=/tmp/composer -v "$PWD": $REMOVE_PHPSTAN composer update --no-interaction --no-progress --no-scripts --no-plugins" -# Only the variable names are listed here; docker reads the values from this environment. +# Only the variables the workflows set are passed, and only when set; docker reads the values +# from this environment. Any other CHECKOUT_* variable of the calling shell stays out. ENV_ARGS=() -for name in $(compgen -e | grep '^CHECKOUT_' || true); do - ENV_ARGS+=(-e "$name") +for name in \ + CHECKOUT_PROCESSING_CHANNEL_ID \ + CHECKOUT_PREVIOUS_SECRET_KEY \ + CHECKOUT_PREVIOUS_PUBLIC_KEY \ + CHECKOUT_DEFAULT_SECRET_KEY \ + CHECKOUT_DEFAULT_PUBLIC_KEY \ + CHECKOUT_DEFAULT_OAUTH_CLIENT_ID \ + CHECKOUT_DEFAULT_OAUTH_CLIENT_SECRET \ + CHECKOUT_DEFAULT_OAUTH_PAYOUT_SCHEDULE_CLIENT_ID \ + CHECKOUT_DEFAULT_OAUTH_PAYOUT_SCHEDULE_CLIENT_SECRET \ + CHECKOUT_DEFAULT_OAUTH_ACCOUNTS_CLIENT_ID \ + CHECKOUT_DEFAULT_OAUTH_ACCOUNTS_CLIENT_SECRET \ + CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_ID \ + CHECKOUT_DEFAULT_OAUTH_ISSUING_CLIENT_SECRET \ + CHECKOUT_MERCHANT_SUBDOMAIN; do + if [ -n "${!name+set}" ]; then + ENV_ARGS+=(-e "$name") + fi done -docker run --rm -u "$(id -u):$(id -g)" "${ENV_ARGS[@]}" -v "$PWD":/app -w /app "$PHP_IMAGE" sh -c " +docker run --rm -u "$(id -u):$(id -g)" ${ENV_ARGS[@]+"${ENV_ARGS[@]}"} -v "$PWD":/app -w /app "$PHP_IMAGE" sh -c " php -v && if [ -x vendor/bin/phpstan ]; then vendor/bin/phpstan analyse --no-progress --memory-limit=1G; fi && vendor/bin/phpunit --verbose" diff --git a/README.md b/README.md index 61ef707c..c729b315 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ A `cURL error 60` means PHP cannot find a CA bundle that trusts the API certific All the API responses that do not fall in the 2** status codes, the SDK will throw a `CheckoutApiException`. -The exception encapsulates `http_metadata` and `$error_details`, if available. +The exception encapsulates `http_metadata` (status, reason phrase and response headers, cookies excluded) and `$error_details`, if available. A request argument that cannot be sent as given (for example an empty id, or a query filter value that is not a string, number, boolean or `DateTime`) throws a `CheckoutArgumentException` before any request is sent. Both exceptions extend `CheckoutException`: catch `CheckoutException` to handle the two. diff --git a/lib/Checkout/AbstractStaticKeysCheckoutSdkBuilder.php b/lib/Checkout/AbstractStaticKeysCheckoutSdkBuilder.php index a29ac6f7..880a14d1 100644 --- a/lib/Checkout/AbstractStaticKeysCheckoutSdkBuilder.php +++ b/lib/Checkout/AbstractStaticKeysCheckoutSdkBuilder.php @@ -9,13 +9,17 @@ abstract class AbstractStaticKeysCheckoutSdkBuilder extends AbstractCheckoutSdkB protected $secretKey = null; /** - * @param string $key + * @param string|object $key the secret key, a string or an object with __toString * @param string $secretKeyPattern - * @throws CheckoutArgumentException + * @throws CheckoutArgumentException when the key is not text or does not match the pattern */ - protected function validateSecretKey($key, $secretKeyPattern) - { - if ($this->validKey($secretKeyPattern, $key)) { + protected function validateSecretKey( + #[\SensitiveParameter] + $key, + $secretKeyPattern + ) { + $isText = is_string($key) || (is_object($key) && method_exists($key, "__toString")); + if ($isText && $this->validKey($secretKeyPattern, (string)$key)) { return; } throw new CheckoutArgumentException("invalid secret key"); @@ -37,12 +41,27 @@ protected function validatePublicKey($key, $publicKeyPattern) throw new CheckoutArgumentException("invalid public key"); } - private function validKey($pattern, $key) - { + /** + * @param string $pattern + * @param string $key + * @return int|false 1 when the key matches the pattern + */ + private function validKey( + $pattern, + #[\SensitiveParameter] + $key + ) { return preg_match($pattern, $key); } abstract protected function publicKey($publicKey); - abstract protected function secretKey($secretKey); + /** + * @param string|object $secretKey the secret key, a string or an object with __toString + * @return $this + */ + abstract protected function secretKey( + #[\SensitiveParameter] + $secretKey + ); } diff --git a/lib/Checkout/AbstractStaticKeysSdkCredentials.php b/lib/Checkout/AbstractStaticKeysSdkCredentials.php index bac084b9..85d1ff1e 100644 --- a/lib/Checkout/AbstractStaticKeysSdkCredentials.php +++ b/lib/Checkout/AbstractStaticKeysSdkCredentials.php @@ -11,8 +11,11 @@ abstract class AbstractStaticKeysSdkCredentials implements SdkCredentialsInterfa * @param string|null $secretKey * @param string|null $publicKey */ - public function __construct($secretKey, $publicKey) - { + public function __construct( + #[\SensitiveParameter] + $secretKey, + $publicKey + ) { $this->publicKey = $publicKey; $this->secretKey = $secretKey; } diff --git a/lib/Checkout/ApiClient.php b/lib/Checkout/ApiClient.php index 57771fc1..203b5286 100644 --- a/lib/Checkout/ApiClient.php +++ b/lib/Checkout/ApiClient.php @@ -4,7 +4,6 @@ use Checkout\Common\AbstractQueryFilter; use Checkout\Files\FileRequest; -use Exception; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Response; @@ -21,8 +20,15 @@ class ApiClient private $baseUri; - public function __construct(CheckoutConfiguration $configuration, $baseUri = null) - { + /** + * @param CheckoutConfiguration $configuration + * @param string|null $baseUri base URI of the API; the environment's base URI when null + */ + public function __construct( + #[\SensitiveParameter] + CheckoutConfiguration $configuration, + $baseUri = null + ) { $this->configuration = $configuration; $this->client = $configuration->getHttpClientBuilder()->getClient(); $this->jsonSerializer = new JsonSerializer(); @@ -36,8 +42,11 @@ public function __construct(CheckoutConfiguration $configuration, $baseUri = nul * @return array * @throws CheckoutApiException */ - public function get($path, SdkAuthorization $authorization) - { + public function get( + $path, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { return $this->invoke("GET", $path, null, $authorization); } @@ -49,11 +58,15 @@ public function get($path, SdkAuthorization $authorization) * @return array * @throws CheckoutApiException */ - public function post($path, $body, SdkAuthorization $authorization, $idempotencyKey = null) - { - return $this->invoke("POST", $path, is_null($body) - ? $body - : $this->jsonSerializer->serialize($body), $authorization, $idempotencyKey); + public function post( + $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization, + $idempotencyKey = null + ) { + return $this->invoke("POST", $path, $body, $authorization, $idempotencyKey); } /** @@ -63,9 +76,14 @@ public function post($path, $body, SdkAuthorization $authorization, $idempotency * @return array * @throws CheckoutApiException */ - public function put($path, $body, SdkAuthorization $authorization) - { - return $this->invoke("PUT", $path, $this->jsonSerializer->serialize($body), $authorization); + public function put( + $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { + return $this->invoke("PUT", $path, $body, $authorization); } /** @@ -75,9 +93,14 @@ public function put($path, $body, SdkAuthorization $authorization) * @return array * @throws CheckoutApiException */ - public function patch($path, $body, SdkAuthorization $authorization) - { - return $this->invoke("PATCH", $path, $this->jsonSerializer->serialize($body), $authorization); + public function patch( + $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { + return $this->invoke("PATCH", $path, $body, $authorization); } /** @@ -86,8 +109,11 @@ public function patch($path, $body, SdkAuthorization $authorization) * @return array * @throws CheckoutApiException */ - public function delete($path, SdkAuthorization $authorization) - { + public function delete( + $path, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { return $this->invoke("DELETE", $path, null, $authorization); } @@ -99,8 +125,12 @@ public function delete($path, SdkAuthorization $authorization) * @throws CheckoutApiException * @throws CheckoutArgumentException if a filter property holds a value that cannot be sent as a query value */ - public function query($path, AbstractQueryFilter $body, SdkAuthorization $authorization) - { + public function query( + $path, + AbstractQueryFilter $body, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { $this->logger->info("GET " . $path); $queryParameters = $body->getEncodedQueryParameters(); if (!empty($queryParameters)) { @@ -116,8 +146,12 @@ public function query($path, AbstractQueryFilter $body, SdkAuthorization $author * @return array * @throws CheckoutApiException */ - public function submitFile($path, FileRequest $fileRequest, SdkAuthorization $authorization) - { + public function submitFile( + $path, + FileRequest $fileRequest, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { return $this->submit($path, $fileRequest, $authorization, "file"); } @@ -128,8 +162,12 @@ public function submitFile($path, FileRequest $fileRequest, SdkAuthorization $au * @return array * @throws CheckoutApiException */ - public function submitFileFilesApi($path, FileRequest $fileRequest, SdkAuthorization $authorization) - { + public function submitFileFilesApi( + $path, + FileRequest $fileRequest, + #[\SensitiveParameter] + SdkAuthorization $authorization + ) { return $this->submit($path, $fileRequest, $authorization, "path"); } @@ -141,10 +179,15 @@ public function submitFileFilesApi($path, FileRequest $fileRequest, SdkAuthoriza * @return array * @throws CheckoutApiException */ - private function submit($path, FileRequest $fileRequest, SdkAuthorization $authorization, $multipart) - { + private function submit( + $path, + FileRequest $fileRequest, + #[\SensitiveParameter] + SdkAuthorization $authorization, + $multipart + ) { try { - $this->logger->info("POST " . $path . " file: " . $fileRequest->file); + $this->logger->info("POST " . $path); $headers = $this->getHeaders($authorization, null, null); $response = $this->client->request("POST", $this->getRequestUrl($path), [ "headers" => $headers, @@ -159,43 +202,68 @@ private function submit($path, FileRequest $fileRequest, SdkAuthorization $autho ] ]]); return $this->getResponseContents($response); - } catch (Exception $e) { - $this->logger->error($path . " error: " . $e->getMessage()); - if ($e instanceof RequestException) { - throw CheckoutApiException::from($e); - } - throw new CheckoutApiException($e); + } catch (\Exception $e) { + throw $this->failure($path, $e); + } catch (\Throwable $e) { + throw $this->failure($path, $e); } } /** * @param string $method * @param string $path - * @param $body + * @param mixed $body request body, serialized to JSON here; null sends no body * @param SdkAuthorization $authorization - * @param null $idempotencyKey + * @param string|null $idempotencyKey * @return array - * @throws CheckoutApiException + * @throws CheckoutApiException for any failure: with the status and the error details of an HTTP + * response, otherwise with a description of the failure (CheckoutUtils::describeFailure) */ - private function invoke($method, $path, $body, SdkAuthorization $authorization, $idempotencyKey = null) - { + private function invoke( + $method, + $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization, + $idempotencyKey = null + ) { try { $this->logger->info($method . " " . $path); + $serialized = is_null($body) ? null : $this->jsonSerializer->serialize($body); $headers = $this->getHeaders($authorization, "application/json", $idempotencyKey); $response = $this->client->request($method, $this->getRequestUrl($path), [ - "body" => $body, + "body" => $serialized, "headers" => $headers ]); return $this->getResponseContents($response); - } catch (Exception $e) { - $this->logger->error($path . " error: " . $e->getMessage()); - if ($e instanceof RequestException) { - throw CheckoutApiException::from($e); - } - throw new CheckoutApiException($e); + } catch (\Exception $e) { + throw $this->failure($path, $e); + } catch (\Throwable $e) { + throw $this->failure($path, $e); } } + /** + * Logs a failed request and gives the exception to throw for it. + * + * @param string $path + * @param \Throwable|\Exception $failure the failure (untyped: PHP 5.6 has no Throwable) + * @return CheckoutApiException with the status and the error details of an HTTP response, + * otherwise with a description of the failure (CheckoutUtils::describeFailure) + */ + private function failure( + $path, + #[\SensitiveParameter] + $failure + ) { + $this->logger->error($path . " error: " . CheckoutUtils::describeFailure($failure)); + if ($failure instanceof RequestException) { + return CheckoutApiException::from($failure); + } + return new CheckoutApiException(CheckoutUtils::describeFailure($failure)); + } + /** * @param string $path * @return string @@ -210,10 +278,16 @@ private function getRequestUrl($path) * @param string|null $contentType * @param string|null $idempotencyKey * @return array - * @throws CheckoutAuthorizationException + * @throws CheckoutAuthorizationException when the authorization value cannot be sent + * @throws CheckoutArgumentException when a header value holds a control character other than tab; + * the message names no value */ - private function getHeaders(SdkAuthorization $authorization, $contentType, $idempotencyKey) - { + private function getHeaders( + #[\SensitiveParameter] + SdkAuthorization $authorization, + $contentType, + $idempotencyKey + ) { $headers = [ "User-agent" => CheckoutUtils::PROJECT_NAME . "/" . CheckoutUtils::PROJECT_VERSION, "Accept" => "application/json", @@ -225,6 +299,15 @@ private function getHeaders(SdkAuthorization $authorization, $contentType, $idem if (!empty($idempotencyKey)) { $headers["Cko-Idempotency-Key"] = $idempotencyKey; } + // Every header value, Authorization included, is checked here once. Anything but a clean + // "no match" (a PCRE error returns false) is refused. + foreach ($headers as $value) { + foreach (is_array($value) ? $value : array($value) as $item) { + if (preg_match('/[\x00-\x08\x0A-\x1F\x7F]/', (string)$item) !== 0) { + throw new CheckoutArgumentException("Invalid header value"); + } + } + } return $headers; } @@ -235,10 +318,15 @@ private function getHeaders(SdkAuthorization $authorization, $contentType, $idem private function getResponseContents($response) { $contentType = $response->getHeader("Content-Type"); - if (in_array("text/csv", $contentType)) { - return $this->createResponse($response, $response->getBody()->getContents()); + // A body that is not text is treated as no body (CheckoutUtils::contentsOf). + $contents = CheckoutUtils::contentsOf($response->getBody()); + if (in_array("text/csv", $contentType, true)) { + return $this->createResponse($response, $contents); } - return $this->createResponse($response, $this->jsonSerializer->deserialize($response->getBody())); + return $this->createResponse( + $response, + $contents === null ? null : $this->jsonSerializer->deserialize($contents) + ); } /** diff --git a/lib/Checkout/CheckoutApi.php b/lib/Checkout/CheckoutApi.php index 0d851a28..ac0c8d81 100644 --- a/lib/Checkout/CheckoutApi.php +++ b/lib/Checkout/CheckoutApi.php @@ -47,8 +47,13 @@ final class CheckoutApi extends CheckoutApmApi private $paymentSessionsClient; - public function __construct(CheckoutConfiguration $configuration) - { + /** + * @param CheckoutConfiguration $configuration + */ + public function __construct( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { $baseApiClient = $this->getBaseApiClient($configuration); parent::__construct($baseApiClient, $configuration); $this->tokensClient = new TokensClient($baseApiClient, $configuration); @@ -247,8 +252,10 @@ public function getPaymentSessionsClient() * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getBaseApiClient(CheckoutConfiguration $configuration) - { + private function getBaseApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { $baseUri = $configuration->getEnvironment()->getBaseUri(); $subdomain = $configuration->getEnvironmentSubdomain(); @@ -262,8 +269,10 @@ private function getBaseApiClient(CheckoutConfiguration $configuration) * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getFilesApiClient(CheckoutConfiguration $configuration) - { + private function getFilesApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { return new ApiClient($configuration, $configuration->getEnvironment()->getFilesBaseUri()); } @@ -271,8 +280,10 @@ private function getFilesApiClient(CheckoutConfiguration $configuration) * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getTransfersApiClient(CheckoutConfiguration $configuration) - { + private function getTransfersApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { return new ApiClient($configuration, $configuration->getEnvironment()->getTransfersUri()); } @@ -280,8 +291,10 @@ private function getTransfersApiClient(CheckoutConfiguration $configuration) * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getBalancesApiClient(CheckoutConfiguration $configuration) - { + private function getBalancesApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { return new ApiClient($configuration, $configuration->getEnvironment()->getBalancesUri()); } } diff --git a/lib/Checkout/CheckoutApiException.php b/lib/Checkout/CheckoutApiException.php index 25ba195b..1e3144de 100644 --- a/lib/Checkout/CheckoutApiException.php +++ b/lib/Checkout/CheckoutApiException.php @@ -3,35 +3,94 @@ namespace Checkout; use GuzzleHttp\Exception\RequestException; +use Psr\Http\Message\ResponseInterface; class CheckoutApiException extends CheckoutException { /** - * @var array + * @var array|null the decoded JSON body of the response; an empty array when there is no + * response or its body cannot be read, null when the body is not JSON */ public $error_details; /** - * @var HttpMetadata + * @var HttpMetadata|null the reason phrase, status code, headers (cookies excluded) and + * protocol version of the response; null when there is none or it cannot be read */ public $http_metadata; /** - * @param RequestException $requestException - * @return CheckoutApiException + * @param RequestException $requestException a failed request of the HTTP client + * @return CheckoutApiException with the status in its message (0 when there is none), the + * response body in error_details and the response metadata in http_metadata */ - public static function from(RequestException $requestException) - { - $response = $requestException->getResponse(); - + public static function from( + #[\SensitiveParameter] + RequestException $requestException + ) { + $response = CheckoutUtils::responseOf($requestException); + $status = CheckoutUtils::statusOf($response); + if ($status === null) { + $code = $requestException->getCode(); + $status = is_int($code) ? $code : 0; + } $ex = new CheckoutApiException(sprintf( - "The API response status code (%s) does not indicate success.", - $requestException->getCode() + "The API response status code (%d) does not indicate success.", + $status )); - $ex->error_details = isset($response) - ? json_decode($response->getBody()->getContents(), true) - : []; - $ex->http_metadata = CheckoutUtils::getHttpMetadata($response); - + $body = CheckoutUtils::bodyOf($response); + $ex->error_details = $body === null ? [] : json_decode($body, true); + $ex->http_metadata = self::metadataWithoutCookies($response); return $ex; } + + /** + * Builds the metadata of a failed response, without its cookies. + * + * @param ResponseInterface|null $response the response of the failed request, if any + * @return HttpMetadata|null the reason phrase, status code, headers without Set-Cookie and + * protocol version; null when there is no response or it cannot be read + */ + private static function metadataWithoutCookies( + #[\SensitiveParameter] + $response + ) { + if (!$response instanceof ResponseInterface) { + return null; + } + try { + $headers = array_filter($response->getHeaders(), function ($name) { + return !in_array(self::plainHeaderName($name), array("set-cookie", "set-cookie2"), true); + }, ARRAY_FILTER_USE_KEY); + $reason = $response->getReasonPhrase(); + $status = $response->getStatusCode(); + $protocol = $response->getProtocolVersion(); + // Implementations without return types (psr/http-message 1.0) may return anything. + if (!is_string($reason) || !is_int($status) || !is_string($protocol)) { + return null; + } + return new HttpMetadata($reason, $status, $headers, $protocol); + } catch (\Exception $unreadable) { + return null; + } catch (\Throwable $unreadable) { + return null; + } + } + + /** + * @param mixed $name a header name + * @return string the name in lower case with only its letters, digits and hyphens, so padding, + * control or format characters that a lenient PSR-7 implementation leaves in it do not hide + * which header it is + */ + private static function plainHeaderName($name) + { + $plain = ""; + foreach (str_split(strtolower((string)$name)) as $character) { + if (($character >= "a" && $character <= "z") || ($character >= "0" && $character <= "9") + || $character === "-") { + $plain .= $character; + } + } + return $plain; + } } diff --git a/lib/Checkout/CheckoutAuthorizationException.php b/lib/Checkout/CheckoutAuthorizationException.php index 260bbf6a..b7b94880 100644 --- a/lib/Checkout/CheckoutAuthorizationException.php +++ b/lib/Checkout/CheckoutAuthorizationException.php @@ -6,12 +6,18 @@ class CheckoutAuthorizationException extends CheckoutException { /** - * @param $authorizationType + * @param mixed $authorizationType one of the AuthorizationType values; any other value is not + * repeated in the message * @return CheckoutAuthorizationException */ - public static function invalidAuthorization($authorizationType) - { - return new CheckoutAuthorizationException("Operation requires " . $authorizationType . " authorization type"); + public static function invalidAuthorization( + #[\SensitiveParameter] + $authorizationType + ) { + $known = in_array($authorizationType, array_values(get_class_vars(AuthorizationType::class)), true); + return new CheckoutAuthorizationException( + "Operation requires " . ($known ? $authorizationType : "a supported") . " authorization type" + ); } /** diff --git a/lib/Checkout/CheckoutConfiguration.php b/lib/Checkout/CheckoutConfiguration.php index 20cc0e31..687d75d9 100644 --- a/lib/Checkout/CheckoutConfiguration.php +++ b/lib/Checkout/CheckoutConfiguration.php @@ -23,6 +23,7 @@ final class CheckoutConfiguration * @param LoggerInterface $logger */ public function __construct( + #[\SensitiveParameter] SdkCredentialsInterface $sdkCredentials, Environment $environment, HttpClientBuilderInterface $httpClientBuilder, diff --git a/lib/Checkout/CheckoutOAuthSdkBuilder.php b/lib/Checkout/CheckoutOAuthSdkBuilder.php index a180816f..c357234e 100644 --- a/lib/Checkout/CheckoutOAuthSdkBuilder.php +++ b/lib/Checkout/CheckoutOAuthSdkBuilder.php @@ -17,6 +17,7 @@ class CheckoutOAuthSdkBuilder extends AbstractCheckoutSdkBuilder */ public function clientCredentials( $clientId, + #[\SensitiveParameter] $clientSecret ) { $this->clientId = $clientId; diff --git a/lib/Checkout/CheckoutStaticKeysSdkBuilder.php b/lib/Checkout/CheckoutStaticKeysSdkBuilder.php index ec8b6aa4..422cf942 100644 --- a/lib/Checkout/CheckoutStaticKeysSdkBuilder.php +++ b/lib/Checkout/CheckoutStaticKeysSdkBuilder.php @@ -22,8 +22,10 @@ public function publicKey($publicKey) * @param string $secretKey * @return $this */ - public function secretKey($secretKey) - { + public function secretKey( + #[\SensitiveParameter] + $secretKey + ) { $this->secretKey = $secretKey; return $this; } diff --git a/lib/Checkout/CheckoutUtils.php b/lib/Checkout/CheckoutUtils.php index 871c9ee1..127a45db 100644 --- a/lib/Checkout/CheckoutUtils.php +++ b/lib/Checkout/CheckoutUtils.php @@ -3,7 +3,9 @@ namespace Checkout; use DateTime; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Response; +use Psr\Http\Message\ResponseInterface; class CheckoutUtils { @@ -80,4 +82,147 @@ public static function getHttpMetadata($http_response = null) $http_response->getProtocolVersion() ); } + + /** + * The response of an HTTP client failure. For internal use by the SDK. + * + * @internal + * @param \Throwable|\Exception $failure any failure (untyped: PHP 5.6 has no Throwable); only HTTP + * client request failures have a response + * @return ResponseInterface|null null when the failure has no response or it cannot be read + */ + public static function responseOf( + #[\SensitiveParameter] + $failure + ) { + if (!$failure instanceof RequestException) { + return null; + } + try { + return $failure->getResponse(); + } catch (\Exception $unreadable) { + return null; + } catch (\Throwable $unreadable) { + return null; + } + } + + /** + * The status code of a response. For internal use by the SDK. + * + * @internal + * @param ResponseInterface|null $response the response to read, if any + * @return int|null null when there is no response or its status cannot be read + */ + public static function statusOf( + #[\SensitiveParameter] + $response + ) { + if (!$response instanceof ResponseInterface) { + return null; + } + try { + $status = $response->getStatusCode(); + } catch (\Exception $unreadable) { + return null; + } catch (\Throwable $unreadable) { + return null; + } + return is_int($status) ? $status : null; + } + + /** + * The whole body of a response, read from the start. For internal use by the SDK. + * + * @internal + * @param ResponseInterface|null $response the response to read, if any + * @return string|null null when there is no response or its body cannot be read + */ + public static function bodyOf( + #[\SensitiveParameter] + $response + ) { + if (!$response instanceof ResponseInterface) { + return null; + } + try { + return self::contentsOf($response->getBody()); + } catch (\Exception $unreadable) { + return null; + } catch (\Throwable $unreadable) { + return null; + } + } + + /** + * The whole text of a stream, read from the start. For internal use by the SDK. + * + * Reads with rewind() and getContents(), not __toString(): an exception thrown inside + * __toString() cannot be caught before PHP 7.4. + * + * @internal + * @param \Psr\Http\Message\StreamInterface $stream the stream to read + * @return string|null the text; null when getContents() gives anything else, which is not + * converted, because its __toString() could throw + * @throws \RuntimeException when the stream cannot be read; read failures are not caught here + */ + public static function contentsOf( + #[\SensitiveParameter] + $stream + ) { + if ($stream->isSeekable()) { + $stream->rewind(); + } + $contents = $stream->getContents(); + return is_string($contents) ? $contents : null; + } + + /** + * Describes a failure for an SDK error message or log line without copying text the SDK does + * not control. For internal use by the SDK. + * + * @internal + * @param \Throwable|\Exception $failure the failure (untyped: PHP 5.6 has no Throwable) + * @return string the class and message of an SDK exception created by code under lib/Checkout; + * for any other failure, its class with the HTTP status or the transport error number when + * there is one + */ + public static function describeFailure( + #[\SensitiveParameter] + $failure + ) { + $class = get_class($failure); + // An anonymous class name holds a NUL byte followed by the file that declares it. + $nul = strpos($class, "\0"); + if ($nul !== false) { + $class = substr($class, 0, $nul); + } + // Only messages the SDK wrote: an SDK exception created by code under lib/Checkout (PHP records + // the file where the exception is created, not where it is thrown). __DIR__ is lib/Checkout, + // so this helper stays in that directory. SDK factory methods repeat no caller text. + if ($failure instanceof CheckoutException + && strpos($failure->getFile(), __DIR__ . DIRECTORY_SEPARATOR) === 0 + ) { + return $class . ": " . $failure->getMessage(); + } + $status = self::statusOf(self::responseOf($failure)); + if ($status !== null) { + return $class . " (status " . $status . ")"; + } + // Transfer errors of the HTTP client carry the transport error number in their context. + if (method_exists($failure, "getHandlerContext")) { + try { + $context = $failure->getHandlerContext(); + } catch (\Exception $unreadable) { + $context = null; + } catch (\Throwable $unreadable) { + $context = null; + } + $errno = is_array($context) && isset($context["errno"]) ? $context["errno"] : null; + if (is_int($errno)) { + return $class . " (cURL error " . $errno . ")"; + } + } + return $class; + } } diff --git a/lib/Checkout/Issuing/IssuingClient.php b/lib/Checkout/Issuing/IssuingClient.php index 244fc0d2..1904e0cc 100644 --- a/lib/Checkout/Issuing/IssuingClient.php +++ b/lib/Checkout/Issuing/IssuingClient.php @@ -126,8 +126,11 @@ public function getCardDetails($cardId) * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function enrollThreeDS($cardId, ThreeDSEnrollmentRequest $threeDSEnrollmentRequest) - { + public function enrollThreeDS( + $cardId, + #[\SensitiveParameter] + ThreeDSEnrollmentRequest $threeDSEnrollmentRequest + ) { return $this->apiClient->post( $this->buildPath( self::ISSUING_PATH, @@ -147,8 +150,11 @@ public function enrollThreeDS($cardId, ThreeDSEnrollmentRequest $threeDSEnrollme * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function updateThreeDSEnrollment($cardId, UpdateThreeDSEnrollmentRequest $threeDSEnrollmentRequest) - { + public function updateThreeDSEnrollment( + $cardId, + #[\SensitiveParameter] + UpdateThreeDSEnrollmentRequest $threeDSEnrollmentRequest + ) { return $this->apiClient->patch( $this->buildPath( self::ISSUING_PATH, diff --git a/lib/Checkout/OAuthAccessToken.php b/lib/Checkout/OAuthAccessToken.php index 14a93c18..4916e077 100644 --- a/lib/Checkout/OAuthAccessToken.php +++ b/lib/Checkout/OAuthAccessToken.php @@ -14,8 +14,11 @@ class OAuthAccessToken * @param string $token * @param DateTime $expirationDate */ - public function __construct($token, DateTime $expirationDate) - { + public function __construct( + #[\SensitiveParameter] + $token, + DateTime $expirationDate + ) { $this->token = $token; $this->expirationDate = $expirationDate; } diff --git a/lib/Checkout/OAuthSdkCredentials.php b/lib/Checkout/OAuthSdkCredentials.php index 81a91eac..8e4e4c3d 100644 --- a/lib/Checkout/OAuthSdkCredentials.php +++ b/lib/Checkout/OAuthSdkCredentials.php @@ -4,7 +4,6 @@ use DateInterval; use DateTime; -use Exception; class OAuthSdkCredentials implements SdkCredentialsInterface { @@ -16,6 +15,19 @@ class OAuthSdkCredentials implements SdkCredentialsInterface */ private static $maxExpiresInSeconds = 31536000; + /** + * Error codes of a token error response (RFC 6749, section 5.2). A private static property + * rather than a constant, because PHP 5.6 has no constant visibility. + */ + private static $oauthErrorCodes = array( + "invalid_request", + "invalid_client", + "invalid_grant", + "unauthorized_client", + "unsupported_grant_type", + "invalid_scope", + ); + private $client; private $clientId; private $clientSecret; @@ -25,14 +37,16 @@ class OAuthSdkCredentials implements SdkCredentialsInterface /** * @param HttpClientBuilderInterface $httpClientBuilder - * @param $clientId - * @param $clientSecret - * @param $authorizationUri + * @param string $clientId + * @param string $clientSecret + * @param string $authorizationUri * @param array $scopes */ public function __construct( + #[\SensitiveParameter] HttpClientBuilderInterface $httpClientBuilder, $clientId, + #[\SensitiveParameter] $clientSecret, $authorizationUri, array $scopes @@ -46,17 +60,19 @@ public function __construct( /** * @param HttpClientBuilderInterface $httpClientBuilder - * @param $clientId - * @param $clientSecret - * @param $authorizationUri + * @param string $clientId + * @param string $clientSecret + * @param string $authorizationUri * @param array $scopes * @return OAuthSdkCredentials * @throws CheckoutAuthorizationException * @throws CheckoutException */ public static function init( + #[\SensitiveParameter] HttpClientBuilderInterface $httpClientBuilder, $clientId, + #[\SensitiveParameter] $clientSecret, $authorizationUri, array $scopes @@ -109,10 +125,14 @@ private function getAccessToken() "scope" => implode(" ", $this->scopes) ] ]); - } catch (Exception $e) { - throw new CheckoutException($e->getMessage()); + // A body that is not text is treated as no body (CheckoutUtils::contentsOf). + $contents = CheckoutUtils::contentsOf($response->getBody()); + $body = $contents === null ? null : json_decode($contents, true); + } catch (\Exception $e) { + throw new CheckoutException(self::tokenFailureMessage($e)); + } catch (\Throwable $e) { + throw new CheckoutException(self::tokenFailureMessage($e)); } - $body = json_decode((string)$response->getBody(), true); if (!self::isValidTokenResponse($body)) { throw CheckoutAuthorizationException::invalidAccessTokenResponse(); } @@ -122,6 +142,30 @@ private function getAccessToken() return $this->accessToken; } + /** + * @param \Throwable|\Exception $failure the failure (untyped: PHP 5.6 has no Throwable) + * @return string the status and, when the server sent one, the standard OAuth error code of a + * failed token request; otherwise a description of the failure. No text of the response or + * of another library is copied. + */ + private static function tokenFailureMessage( + #[\SensitiveParameter] + $failure + ) { + $response = CheckoutUtils::responseOf($failure); + $status = CheckoutUtils::statusOf($response); + if ($status === null) { + return "OAuth token request failed: " . CheckoutUtils::describeFailure($failure); + } + $message = "OAuth token request failed with status " . $status; + $body = json_decode((string)CheckoutUtils::bodyOf($response), true); + $error = is_array($body) && isset($body["error"]) ? $body["error"] : null; + if (is_string($error) && in_array($error, self::$oauthErrorCodes, 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/lib/Checkout/Previous/CheckoutApi.php b/lib/Checkout/Previous/CheckoutApi.php index 96235531..fe4f1824 100644 --- a/lib/Checkout/Previous/CheckoutApi.php +++ b/lib/Checkout/Previous/CheckoutApi.php @@ -34,8 +34,13 @@ final class CheckoutApi extends CheckoutApmApi private $riskClient; private $reconciliationClient; - public function __construct(CheckoutConfiguration $configuration) - { + /** + * @param CheckoutConfiguration $configuration + */ + public function __construct( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { $baseApiClient = $this->getBaseApiClient($configuration); parent::__construct($baseApiClient, $configuration); $this->sourcesClient = new SourcesClient($baseApiClient, $configuration); @@ -152,8 +157,10 @@ public function getReconciliationClient() * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getBaseApiClient(CheckoutConfiguration $configuration) - { + private function getBaseApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { $baseUri = $configuration->getEnvironment()->getBaseUri(); $subdomain = $configuration->getEnvironmentSubdomain(); diff --git a/lib/Checkout/Previous/CheckoutStaticKeysPreviousSdkBuilder.php b/lib/Checkout/Previous/CheckoutStaticKeysPreviousSdkBuilder.php index 1dcf2bf3..e698785b 100644 --- a/lib/Checkout/Previous/CheckoutStaticKeysPreviousSdkBuilder.php +++ b/lib/Checkout/Previous/CheckoutStaticKeysPreviousSdkBuilder.php @@ -28,8 +28,10 @@ public function publicKey($publicKey) * @param string $secretKey * @return $this */ - public function secretKey($secretKey) - { + public function secretKey( + #[\SensitiveParameter] + $secretKey + ) { $this->secretKey = $secretKey; return $this; } diff --git a/lib/Checkout/Previous/PreviousStaticKeysSdkCredentials.php b/lib/Checkout/Previous/PreviousStaticKeysSdkCredentials.php index 705ad052..3ad6da8b 100644 --- a/lib/Checkout/Previous/PreviousStaticKeysSdkCredentials.php +++ b/lib/Checkout/Previous/PreviousStaticKeysSdkCredentials.php @@ -15,8 +15,11 @@ class PreviousStaticKeysSdkCredentials extends AbstractStaticKeysSdkCredentials * @param string|null $secretKey * @param string|null $publicKey */ - public function __construct($secretKey, $publicKey) - { + public function __construct( + #[\SensitiveParameter] + $secretKey, + $publicKey + ) { parent::__construct($secretKey, $publicKey); } diff --git a/lib/Checkout/SdkAuthorization.php b/lib/Checkout/SdkAuthorization.php index e6ca9ece..ecc0fbbc 100644 --- a/lib/Checkout/SdkAuthorization.php +++ b/lib/Checkout/SdkAuthorization.php @@ -14,26 +14,61 @@ final class SdkAuthorization * @param mixed $platformType * @param mixed $credential */ - public function __construct($platformType, $credential) - { + public function __construct( + $platformType, + #[\SensitiveParameter] + $credential + ) { $this->platformType = $platformType; $this->credential = $credential; } /** - * @throws CheckoutAuthorizationException + * @return string|string[] the Authorization header value: the credential's text, after the + * Bearer prefix on the default and OAuth platforms + * @throws CheckoutAuthorizationException when the platform type is unknown or the credential is + * not text; the message names no value */ public function getAuthorizationHeader() { + // Each value is read once; ApiClient::getHeaders checks the text built here. switch ($this->platformType) { case PlatformType::$previous: case PlatformType::$custom: - return $this->credential; + $header = is_array($this->credential) + ? array_map(array(self::class, "asText"), $this->credential) + : self::asText($this->credential); + // A string or a non-empty list of strings; anything else is refused here rather + // than handed to the HTTP client. + $values = is_array($header) ? $header : array($header); + if ($values === array() || count(array_filter($values, "is_string")) !== count($values)) { + throw new CheckoutAuthorizationException("Invalid authorization credential"); + } + break; case PlatformType::$default: case PlatformType::$default_oauth: - return self::BEARER . $this->credential; + $text = self::asText($this->credential); + if (!is_string($text)) { + throw new CheckoutAuthorizationException("Invalid authorization credential"); + } + $header = self::BEARER . $text; + break; default: throw new CheckoutAuthorizationException("Invalid platform type"); } + return $header; + } + + /** + * @param mixed $value + * @return mixed the text of a scalar or of an object with __toString; any other value unchanged + */ + private static function asText( + #[\SensitiveParameter] + $value + ) { + return is_scalar($value) || (is_object($value) && method_exists($value, "__toString")) + ? (string)$value + : $value; } } diff --git a/lib/Checkout/Sessions/SessionSecretSdkCredentials.php b/lib/Checkout/Sessions/SessionSecretSdkCredentials.php index 2bb723c5..52cbf37c 100644 --- a/lib/Checkout/Sessions/SessionSecretSdkCredentials.php +++ b/lib/Checkout/Sessions/SessionSecretSdkCredentials.php @@ -11,8 +11,13 @@ final class SessionSecretSdkCredentials implements SdkCredentialsInterface { public $secret; - public function __construct($secret) - { + /** + * @param string $secret the session secret + */ + public function __construct( + #[\SensitiveParameter] + $secret + ) { $this->secret = $secret; } diff --git a/lib/Checkout/Sessions/SessionsClient.php b/lib/Checkout/Sessions/SessionsClient.php index 4bfd3725..477b5dd1 100644 --- a/lib/Checkout/Sessions/SessionsClient.php +++ b/lib/Checkout/Sessions/SessionsClient.php @@ -41,8 +41,11 @@ public function requestSession(SessionRequest $sessionRequest) * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function getSessionDetails($sessionId, $sessionSecret = null) - { + public function getSessionDetails( + $sessionId, + #[\SensitiveParameter] + $sessionSecret = null + ) { return $this->apiClient->get($this->buildPath( self::SESSIONS_PATH, $this->encodePathSegment($sessionId) @@ -58,8 +61,12 @@ public function getSessionDetails($sessionId, $sessionSecret = null) * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function updateSession($sessionId, ChannelData $channelData, $sessionSecret = null) - { + public function updateSession( + $sessionId, + ChannelData $channelData, + #[\SensitiveParameter] + $sessionSecret = null + ) { return $this->apiClient->put($this->buildPath( self::SESSIONS_PATH, $this->encodePathSegment($sessionId), @@ -75,8 +82,11 @@ public function updateSession($sessionId, ChannelData $channelData, $sessionSecr * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function completeSession($sessionId, $sessionSecret = null) - { + public function completeSession( + $sessionId, + #[\SensitiveParameter] + $sessionSecret = null + ) { return $this->apiClient->post($this->buildPath( self::SESSIONS_PATH, $this->encodePathSegment($sessionId), @@ -93,8 +103,12 @@ public function completeSession($sessionId, $sessionSecret = null) * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function updateThreeDsMethodCompletionIndicator($sessionId, ThreeDsMethodCompletionRequest $threeDsMethodCompletionRequest, $sessionSecret = null) - { + public function updateThreeDsMethodCompletionIndicator( + $sessionId, + ThreeDsMethodCompletionRequest $threeDsMethodCompletionRequest, + #[\SensitiveParameter] + $sessionSecret = null + ) { return $this->apiClient->put($this->buildPath( self::SESSIONS_PATH, $this->encodePathSegment($sessionId), @@ -103,10 +117,14 @@ public function updateThreeDsMethodCompletionIndicator($sessionId, ThreeDsMethod } /** + * @param string|null $sessionSecret + * @return SdkAuthorization * @throws CheckoutAuthorizationException */ - private function getSdkAuthorization($sessionSecret = null) - { + private function getSdkAuthorization( + #[\SensitiveParameter] + $sessionSecret = null + ) { if (is_null($sessionSecret)) { return $this->sdkAuthorization(); } else { diff --git a/lib/Checkout/StaticKeysSdkCredentials.php b/lib/Checkout/StaticKeysSdkCredentials.php index 398c7eed..d67e7b96 100644 --- a/lib/Checkout/StaticKeysSdkCredentials.php +++ b/lib/Checkout/StaticKeysSdkCredentials.php @@ -9,8 +9,11 @@ class StaticKeysSdkCredentials extends AbstractStaticKeysSdkCredentials * @param string|null $secretKey * @param string|null $publicKey */ - public function __construct($secretKey, $publicKey) - { + public function __construct( + #[\SensitiveParameter] + $secretKey, + $publicKey + ) { parent::__construct($secretKey, $publicKey); } diff --git a/lib/Checkout/Webhooks/Previous/WebhooksClient.php b/lib/Checkout/Webhooks/Previous/WebhooksClient.php index c4a31d9e..9a808f32 100644 --- a/lib/Checkout/Webhooks/Previous/WebhooksClient.php +++ b/lib/Checkout/Webhooks/Previous/WebhooksClient.php @@ -47,8 +47,11 @@ public function retrieveWebhook($webhookId) * @return array * @throws CheckoutApiException */ - public function registerWebhook(WebhookRequest $webhookRequest, $idempotencyKey = null) - { + public function registerWebhook( + #[\SensitiveParameter] + WebhookRequest $webhookRequest, + $idempotencyKey = null + ) { return $this->apiClient->post(self::WEBHOOKS_PATH, $webhookRequest, $this->sdkAuthorization(), $idempotencyKey); } @@ -59,8 +62,11 @@ public function registerWebhook(WebhookRequest $webhookRequest, $idempotencyKey * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function updateWebhook($webhookId, WebhookRequest $webhookRequest) - { + public function updateWebhook( + $webhookId, + #[\SensitiveParameter] + WebhookRequest $webhookRequest + ) { return $this->apiClient->put($this->buildPath( self::WEBHOOKS_PATH, $this->encodePathSegment($webhookId) @@ -74,8 +80,11 @@ public function updateWebhook($webhookId, WebhookRequest $webhookRequest) * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function patchWebhook($webhookId, WebhookRequest $webhookRequest) - { + public function patchWebhook( + $webhookId, + #[\SensitiveParameter] + WebhookRequest $webhookRequest + ) { return $this->apiClient->patch($this->buildPath( self::WEBHOOKS_PATH, $this->encodePathSegment($webhookId) diff --git a/lib/Checkout/Workflows/WorkflowsClient.php b/lib/Checkout/Workflows/WorkflowsClient.php index b3d10641..c41f892e 100644 --- a/lib/Checkout/Workflows/WorkflowsClient.php +++ b/lib/Checkout/Workflows/WorkflowsClient.php @@ -44,8 +44,10 @@ public function getWorkflows() * @return array * @throws CheckoutApiException */ - public function createWorkflow(CreateWorkflowRequest $createWorkflowRequest) - { + public function createWorkflow( + #[\SensitiveParameter] + CreateWorkflowRequest $createWorkflowRequest + ) { return $this->apiClient->post(self::WORKFLOWS_PATH, $createWorkflowRequest, $this->sdkAuthorization()); } @@ -84,8 +86,11 @@ public function removeWorkflow($workflowId) * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function updateWorkflow($workflowId, UpdateWorkflowRequest $updateWorkflowRequest) - { + public function updateWorkflow( + $workflowId, + #[\SensitiveParameter] + UpdateWorkflowRequest $updateWorkflowRequest + ) { return $this->apiClient->patch( $this->buildPath(self::WORKFLOWS_PATH, $this->encodePathSegment($workflowId)), $updateWorkflowRequest, @@ -100,8 +105,11 @@ public function updateWorkflow($workflowId, UpdateWorkflowRequest $updateWorkflo * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function addWorkflowAction($workflowId, WorkflowActionRequest $workflowActionRequest) - { + public function addWorkflowAction( + $workflowId, + #[\SensitiveParameter] + WorkflowActionRequest $workflowActionRequest + ) { return $this->apiClient->post( $this->buildPath(self::WORKFLOWS_PATH, $this->encodePathSegment($workflowId), self::ACTIONS_PATH), $workflowActionRequest, @@ -117,8 +125,12 @@ public function addWorkflowAction($workflowId, WorkflowActionRequest $workflowAc * @throws CheckoutApiException * @throws CheckoutArgumentException */ - public function updateWorkflowAction($workflowId, $actionId, WorkflowActionRequest $workflowActionRequest) - { + public function updateWorkflowAction( + $workflowId, + $actionId, + #[\SensitiveParameter] + WorkflowActionRequest $workflowActionRequest + ) { return $this->apiClient->put( $this->buildPath( self::WORKFLOWS_PATH, diff --git a/test/Checkout/Tests/ErrorHandlingFailingContextException.php b/test/Checkout/Tests/ErrorHandlingFailingContextException.php new file mode 100644 index 00000000..2d82853a --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingFailingContextException.php @@ -0,0 +1,14 @@ +code = 500; + } +} diff --git a/test/Checkout/Tests/ErrorHandlingStringableKey.php b/test/Checkout/Tests/ErrorHandlingStringableKey.php new file mode 100644 index 00000000..83a650a4 --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingStringableKey.php @@ -0,0 +1,29 @@ +text = $text; + $this->cleanReads = $cleanReads; + } + + public function __toString() + { + $clean = $this->cleanReads === 0 || $this->reads++ < $this->cleanReads; + return $this->text . ($clean ? "" : "\r\nX: y"); + } +} diff --git a/test/Checkout/Tests/ErrorHandlingTest.php b/test/Checkout/Tests/ErrorHandlingTest.php new file mode 100644 index 00000000..555054bb --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingTest.php @@ -0,0 +1,1696 @@ +logs = new TestHandler(); + } + + /** + * @test + * @dataProvider tokenFailures + */ + public function oauthTokenFailuresLeaveErrorsClean($response) + { + $builder = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([$response])) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($builder) { + $builder->build(); + }, CheckoutException::class); + } + + public static function tokenFailures() + { + $token = self::ACCESS_TOKEN; + $cases = [ + "status 401" => [new Response(401, [], '{"error":"invalid_client"}')], + "status 400 non-JSON body" => [self::errorPage(400)], + "status 403 error page" => [self::errorPage(403, "", "")], + "status 200 body that cannot be read" => [self::unreadableBody(200)], + "unreachable" => [new ConnectException("Connection refused", new Request("POST", "https://x"))], + "failure with a long message" => [self::failingHandler("plain")], + "SDK exception type from the HTTP stack" => [self::failingHandler("sdk")], + "SDK exception factory from the HTTP stack" => [self::failingHandler("sdk factory")], + "failure whose response cannot be read" => [self::failingHandler("unreadable response")], + "failure whose body cannot be read" => [self::failingHandler("unreadable body")], + "failure with a text code" => [self::failingHandler("text code")], + "failure with an unusual context" => [self::failingHandler("object context")], + "failure whose context cannot be read" => [self::failingHandler("failing context")], + "JSON null" => [new Response(200, [], "null")], + "not JSON" => [new Response(200, [], "" . $token . "")], + "truncated" => [new Response(200, [], '{"access_token":"' . $token . '","expires')], + "expires_in as text" => [new Response(200, [], '{"access_token":"' . $token . '","expires_in":"1"}')], + "token with a line break" => [ + new Response(200, [], '{"access_token":"' . $token . '\r\nX: y","expires_in":3600}') + ], + ]; + if (PHP_VERSION_ID >= 70000) { + $cases["error in the HTTP client"] = [self::errorInTheHttpClient()]; + } + return $cases; + } + + /** + * @test + * @dataProvider apiFailures + */ + public function requestFailuresWithOAuthLeaveErrorsClean($response) + { + $api = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([ + new Response(200, [], '{"access_token":"' . self::ACCESS_TOKEN . '","expires_in":3600}'), + $response + ])) + ->logger($this->logger()) + ->build(); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider apiFailures + */ + public function requestFailuresWithStaticKeysLeaveErrorsClean($response) + { + $api = $this->staticKeysApi([$response]); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider apiFailures + */ + public function requestFailuresWithPreviousKeysLeaveErrorsClean($response) + { + $api = $this->previousApi([$response]); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider sessionRequestFailures + */ + public function sessionRequestFailuresLeaveErrorsClean($method, $response) + { + $sessions = $this->staticKeysApi([$response])->getSessionsClient(); + + $this->assertErrorsClean(function () use ($sessions, $method) { + ErrorHandlingTest::callSessions($sessions, $method); + }, CheckoutApiException::class); + } + + public static function sessionRequestFailures() + { + $cases = []; + $methods = ["getSessionDetails", "updateSession", "completeSession", "updateThreeDsMethodCompletionIndicator"]; + foreach ($methods as $method) { + foreach (self::apiFailures() as $name => $response) { + $cases[$method . ", " . $name] = [$method, $response[0]]; + } + } + return $cases; + } + + /** + * Each session value shape ends in an error (refused before sending, or the API answers 401) + * that carries no part of it. + * + * @test + * @dataProvider sessionValueShapes + */ + public function sessionValuesOfAnyShapeLeaveErrorsClean($case) + { + $values = self::sessionValues(); + $secret = $values[$case]; + $sessions = $this->staticKeysApi([new Response(401, [], "")])->getSessionsClient(); + + $this->assertErrorsClean(function () use ($sessions, $secret) { + $sessions->getSessionDetails("sid_123", $secret); + }, CheckoutApiException::class); + } + + public static function sessionValueShapes() + { + return self::caseNames(self::sessionValues()); + } + + private static function sessionValues() + { + $value = self::SESSION_SECRET; + return [ + "carriage return" => $value . "\r", + "line feed" => $value . "\n", + "line break and space" => $value . "\r\n X: y", + "NUL" => $value . "\0", + "DEL" => $value . "\x7F", + "unit separator" => $value . "\x1F", + "tab" => $value . "\tx", + "next line" => $value . "\xC2\x85", + "right-to-left override" => $value . "\xE2\x80\xAE", + "full-width" => "\xEF\xBD\x93\xEF\xBD\x85\xEF\xBD\x8B_" . $value, + "invalid UTF-8" => $value . "\xC0\xAE", + "prefixed two-line value" => "Bearer " . $value . "\r\nX: y", + "one character more" => "z" . $value, + "very long" => $value . str_repeat("a", 100000), + ]; + } + + /** + * A request body that fails while it is serialized ends in an SDK error. The serializer + * iterates objects from PHP 7.1. + * + * @test + */ + public function requestThatCannotBeSerializedLeavesErrorsClean() + { + if (PHP_VERSION_ID < 70100) { + $this->markTestSkipped("request bodies are iterated from PHP 7.1"); + } + $workflows = $this->staticKeysApi([new Response(200, [], "{}")])->getWorkflowsClient(); + $action = new WebhookWorkflowActionRequest(); + $action->url = "https://example.com/webhooks"; + $action->headers = ["Authorization" => self::SIGNING_KEY]; + $request = new CreateWorkflowRequest(); + $request->actions = [$action]; + $request->conditions = new ErrorHandlingUnreadableIterator(); + + $this->assertErrorsClean(function () use ($workflows, $request) { + $workflows->createWorkflow($request); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider invalidDefaultKeys + */ + public function invalidKeysLeaveErrorsClean($case) + { + $keys = self::invalidKeys(self::INVALID_DEFAULT_KEY, self::INVALID_PREVIOUS_KEY); + $builder = CheckoutSdk::builder()->staticKeys() + ->secretKey($keys[$case]) + ->environment(Environment::sandbox()) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($builder) { + $builder->build(); + }, CheckoutArgumentException::class); + } + + /** + * @test + * @dataProvider invalidPreviousKeys + */ + public function invalidPreviousKeysLeaveErrorsClean($case) + { + $keys = self::invalidKeys(self::INVALID_PREVIOUS_KEY, self::INVALID_DEFAULT_KEY); + $builder = CheckoutSdk::builder()->previous()->staticKeys() + ->secretKey($keys[$case]) + ->environment(Environment::sandbox()) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($builder) { + $builder->build(); + }, CheckoutArgumentException::class); + } + + public static function invalidDefaultKeys() + { + return self::caseNames(self::invalidKeys(self::INVALID_DEFAULT_KEY, self::INVALID_PREVIOUS_KEY)); + } + + public static function invalidPreviousKeys() + { + return self::caseNames(self::invalidKeys(self::INVALID_PREVIOUS_KEY, self::INVALID_DEFAULT_KEY)); + } + + /** + * @param string $key a key the builder accepts, made invalid by each case + * @param string $otherPlatform a valid key of the other platform + * @return array + */ + private static function invalidKeys($key, $otherPlatform) + { + return [ + "leading space" => " " . $key, + "line break" => $key . "\r\n", + "NUL" => $key . "\0", + "other platform" => $otherPlatform, + "one character too long" => $key . "a", + "array" => [$key], + ]; + } + + /** + * @test + */ + public function keyRefusedWhenTheRequestIsBuiltLeavesErrorsClean() + { + $api = $this->staticKeysApi([new Response(200, [], "{}")], self::SECRET_KEY . "\n"); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + */ + public function stringableKeyLeavesErrorsClean() + { + $key = new ErrorHandlingStringableKey(self::SECRET_KEY . "\n", 0); + $api = $this->staticKeysApi([new Response(200, [], "{}")], $key); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * The header is built from the same text that was checked. + * + * @test + */ + public function headerIsBuiltFromTheCheckedText() + { + $key = new ErrorHandlingStringableKey(self::SECRET_KEY, 2); + $api = $this->staticKeysApi([new Response(401, [], "")], $key); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider valuesThatCannotBeSent + */ + public function valuesThatCannotBeSentLeaveErrorsClean($platform, $case) + { + $configuration = new CheckoutConfiguration( + $this->createMock(SdkCredentialsInterface::class), + Environment::sandbox(), + $this->httpClient([new Response(200, [], "{}")]), + $this->logger() + ); + $apiClient = new ApiClient($configuration); + + $this->assertErrorsClean(function () use ($apiClient, $platform, $case) { + $values = ErrorHandlingTest::unsendableValues(); + $apiClient->get("customers/cus_123", new SdkAuthorization(PlatformType::$$platform, $values[$case])); + }, CheckoutApiException::class); + } + + public static function valuesThatCannotBeSent() + { + $cases = []; + foreach (["default", "default_oauth", "previous", "custom"] as $platform) { + foreach (array_keys(self::unsendableValues()) as $name) { + $cases[$platform . ", " . $name] = [$platform, $name]; + } + } + return $cases; + } + + public static function unsendableValues() + { + return [ + "array with a line break" => [self::SESSION_SECRET . "\r\nX: y"], + "array of two" => [self::SESSION_SECRET, self::SESSION_SECRET . "\n"], + "object" => (object)["secret" => self::SESSION_SECRET], + ]; + } + + /** + * @test + * @dataProvider requestsWithSensitiveFields + */ + public function requestsWithSensitiveFieldsLeaveErrorsClean($method, $response) + { + $test = $this; + $this->assertErrorsClean(function () use ($test, $method, $response) { + ErrorHandlingTest::callWithSensitiveFields($test, $method, [$response]); + }, CheckoutApiException::class); + } + + public static function requestsWithSensitiveFields() + { + $methods = [ + "enrollThreeDS", "updateThreeDSEnrollment", "createWorkflow", "updateWorkflow", "addWorkflowAction", + "updateWorkflowAction", "registerWebhook", "updateWebhook", "patchWebhook", + ]; + $cases = []; + foreach ($methods as $method) { + foreach (self::apiFailures() as $name => $response) { + $cases[$method . ", " . $name] = [$method, $response[0]]; + } + } + return $cases; + } + + /** + * @test + * @dataProvider headerValues + */ + public function headerValuesThatCannotBeSentLeaveErrorsClean($case) + { + $values = self::idempotencyKeys(); + $key = $values[$case]; + $webhooks = $this->previousApi([new Response(200, [], "{}")])->getWebhooksClient(); + $webhook = new WebhookRequest(); + $webhook->url = "https://example.com/webhooks"; + + $this->assertErrorsClean(function () use ($webhooks, $webhook, $key) { + $webhooks->registerWebhook($webhook, $key); + }, CheckoutApiException::class); + $logs = print_r($this->logs->getRecords(), true); + try { + $webhooks->registerWebhook($webhook, $key); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + $this->assertSame("Checkout\\CheckoutArgumentException: Invalid header value", $e->getMessage()); + $this->assertTrue(strpos($logs, "zqidem") === false, "header value in the log"); + } + } + + public static function headerValues() + { + return self::caseNames(self::idempotencyKeys()); + } + + private static function idempotencyKeys() + { + return [ + "line feed" => self::IDEMPOTENCY_KEY . "\n", + "line break and space" => self::IDEMPOTENCY_KEY . "\r\n X: y", + "NUL" => self::IDEMPOTENCY_KEY . "\0", + ]; + } + + /** + * @test + * @dataProvider valuesThatAreNotText + */ + public function valuesThatAreNotTextAreRefusedBeforeTheRequest($platform, $case) + { + $sent = new \ArrayObject(); + $configuration = new CheckoutConfiguration( + $this->createMock(SdkCredentialsInterface::class), + Environment::sandbox(), + $this->httpClient([function (RequestInterface $request) use ($sent) { + $sent[] = $request; + return new Response(200, [], "{}"); + }]), + $this->logger() + ); + $apiClient = new ApiClient($configuration); + $credential = $case === "null" ? null : [self::SESSION_SECRET]; + + $this->assertErrorsClean(function () use ($apiClient, $platform, $credential) { + $apiClient->get("customers/cus_123", new SdkAuthorization(PlatformType::$$platform, $credential)); + }, CheckoutApiException::class); + $this->assertCount(0, $sent, "a request was sent"); + } + + public static function valuesThatAreNotText() + { + return [ + "default, clean array" => ["default", "clean array"], + "default, null" => ["default", "null"], + "default_oauth, clean array" => ["default_oauth", "clean array"], + "default_oauth, null" => ["default_oauth", "null"], + "previous, null" => ["previous", "null"], + "custom, null" => ["custom", "null"], + ]; + } + + /** + * @test + */ + public function buildFailureLeavesErrorsClean() + { + $sdk = CheckoutSdk::builder()->staticKeys() + ->secretKey(self::SECRET_KEY) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->failingHttpClientBuilder(0)) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($sdk) { + $sdk->build(); + }, \RuntimeException::class); + } + + /** + * @test + */ + public function previousBuildFailureLeavesErrorsClean() + { + $sdk = CheckoutSdk::builder()->previous()->staticKeys() + ->secretKey(self::PREVIOUS_SECRET_KEY) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->failingHttpClientBuilder(0)) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($sdk) { + $sdk->build(); + }, \RuntimeException::class); + } + + /** + * @test + */ + public function oauthBuildFailureAfterTheTokenLeavesErrorsClean() + { + $sdk = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->failingHttpClientBuilder(1, [ + new Response(200, [], '{"access_token":"' . self::ACCESS_TOKEN . '","expires_in":3600}') + ])) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($sdk) { + $sdk->build(); + }, \RuntimeException::class); + } + + /** + * @test + */ + public function transportFailureMessageNamesTheFailureOnly() + { + $sessions = $this->staticKeysApi([ + function (RequestInterface $request) { + // Created while the SDK frames are on the stack, as the HTTP client does. + throw new ConnectException("Connection refused", $request); + } + ])->getSessionsClient(); + + $this->assertTransportFailure(function () use ($sessions) { + $sessions->getSessionDetails("sid_123", ErrorHandlingTest::SESSION_SECRET); + }, "GuzzleHttp\\Exception\\ConnectException"); + } + + /** + * @test + */ + public function transportFailureMessageKeepsTheTransportErrorNumber() + { + $sessions = $this->staticKeysApi([ + function (RequestInterface $request) { + throw new ConnectException("Could not resolve host", $request, null, ["errno" => 6]); + } + ])->getSessionsClient(); + + $this->assertTransportFailure(function () use ($sessions) { + $sessions->getSessionDetails("sid_123", ErrorHandlingTest::SESSION_SECRET); + }, "GuzzleHttp\\Exception\\ConnectException (cURL error 6)"); + } + + /** + * A connection that the transport cannot open, with the HTTP client's own handler. + * + * @test + */ + public function failedConnectionNamesTheFailureAndTheTransportErrorNumber() + { + if (!function_exists("curl_exec")) { + $this->markTestSkipped("the cURL extension is not loaded"); + } + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method("getClient")->willReturn(new Client(["allow_redirects" => false])); + $configuration = new CheckoutConfiguration( + $this->createMock(SdkCredentialsInterface::class), + Environment::sandbox(), + $builder, + $this->logger() + ); + $apiClient = new ApiClient($configuration, "http://127.0.0.1:1/"); + + $this->assertTransportFailure(function () use ($apiClient) { + $apiClient->get( + "customers/cus_123", + new SdkAuthorization(PlatformType::$default, ErrorHandlingTest::SECRET_KEY) + ); + }, "GuzzleHttp\\Exception\\ConnectException (cURL error 7)"); + } + + /** + * @test + */ + public function failedTokenConnectionNamesTheFailureAndTheTransportErrorNumber() + { + if (!function_exists("curl_exec")) { + $this->markTestSkipped("the cURL extension is not loaded"); + } + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method("getClient")->willReturn(new Client(["allow_redirects" => false])); + $sdk = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->authorizationUri("http://127.0.0.1:1/connect/token") + ->environment(Environment::sandbox()) + ->httpClientBuilder($builder) + ->logger($this->logger()); + + try { + $sdk->build(); + $this->fail("expected an exception"); + } catch (CheckoutException $e) { + $this->assertSame( + "OAuth token request failed: GuzzleHttp\\Exception\\ConnectException (cURL error 7)", + $e->getMessage() + ); + } + } + + /** + * @test + */ + public function successfulResponseHeadersAreKeptAsTheyAre() + { + $result = $this->staticKeysApi([new Response(200, [ + "Cko-Request-Id" => "req_123", + "Set-Cookie" => "session=abc", + ], '{"id":"cus_123"}')])->getCustomersClient()->get("cus_123"); + + $headers = $result["http_metadata"]->getHeaders(); + $this->assertSame(["session=abc"], $headers["Set-Cookie"]); + } + + /** + * @test + */ + public function errorMetadataOfAnotherPsr7ResponseIsKeptWithoutCookies() + { + $response = Mockery::mock(ResponseInterface::class); + $response->shouldReceive("getStatusCode")->andReturn(401); + $response->shouldReceive("getReasonPhrase")->andReturn("Unauthorized"); + $response->shouldReceive("getProtocolVersion")->andReturn("1.1"); + $response->shouldReceive("getBody")->andReturn(Utils::streamFor('{"error_type":"request_unauthorized"}')); + $cookie = ["session=" . self::RESPONSE_COOKIE]; + $response->shouldReceive("getHeaders")->andReturn([ + "Cko-Request-Id" => ["req_123"], + "Set-Cookie" => $cookie, + "Set-Cookie " => $cookie, + "\tSet-Cookie" => $cookie, + "Set-Cookie\0" => $cookie, + "Set-Cookie\r\n" => $cookie, + "Set\xE2\x80\x8B-Cookie2" => $cookie, + ]); + + $e = $this->failedCustomersCall(function (RequestInterface $request) use ($response) { + throw new RequestException("failed", $request, $response); + }); + + $this->assertSame("The API response status code (401) does not indicate success.", $e->getMessage()); + $this->assertSame(["Cko-Request-Id" => ["req_123"]], $e->http_metadata->getHeaders()); + $this->assertSame(["error_type" => "request_unauthorized"], $e->error_details); + } + + /** + * @test + */ + public function errorMetadataIsLeftEmptyWhenItsHeadersCannotBeRead() + { + $response = Mockery::mock(Response::class, [401, [], '{"error_type":"request_unauthorized"}'])->makePartial(); + $response->shouldReceive("getHeaders")->andThrow(new \RuntimeException("no headers")); + + $e = $this->failedCustomersCall(function (RequestInterface $request) use ($response) { + throw new RequestException("failed", $request, $response); + }); + + $this->assertNull($e->http_metadata); + $this->assertSame(["error_type" => "request_unauthorized"], $e->error_details); + } + + /** + * @test + */ + public function errorMessageTakesTheStatusFromTheResponse() + { + $e = $this->failedCustomersCall(function (RequestInterface $request) { + throw new ErrorHandlingOtherCodeException("failed", $request, new Response(401)); + }); + + $this->assertSame("The API response status code (401) does not indicate success.", $e->getMessage()); + } + + /** + * @test + */ + public function errorMetadataWithValuesOfTheWrongTypeIsLeftEmpty() + { + $response = Mockery::mock(ResponseInterface::class); + $response->shouldReceive("getStatusCode")->andReturn("401"); + $response->shouldReceive("getReasonPhrase")->andReturn(null); + $response->shouldReceive("getProtocolVersion")->andReturn(1.1); + $response->shouldReceive("getBody")->andReturn(Utils::streamFor('{"error_type":"request_unauthorized"}')); + $response->shouldReceive("getHeaders")->andReturn(["Cko-Request-Id" => ["req_123"]]); + + $e = $this->failedCustomersCall(function (RequestInterface $request) use ($response) { + throw new RequestException("failed", $request, $response); + }); + + $this->assertNull($e->http_metadata); + $this->assertSame(["error_type" => "request_unauthorized"], $e->error_details); + } + + /** + * Response bodies are read without their string conversion, which cannot throw before PHP 7.4. + * + * @test + */ + public function errorBodyIsReadWithoutItsStringConversion() + { + $e = $this->failedCustomersCall(function (RequestInterface $request) { + throw new RequestException( + "failed", + $request, + new Response( + 401, + [], + ErrorHandlingTest::bodyWithoutStringConversion('{"error_type":"request_unauthorized"}') + ) + ); + }); + + $this->assertSame("The API response status code (401) does not indicate success.", $e->getMessage()); + $this->assertSame(["error_type" => "request_unauthorized"], $e->error_details); + } + + /** + * @test + */ + public function successfulBodyIsReadWithoutItsStringConversion() + { + $result = $this->staticKeysApi([new Response( + 200, + ["Content-Type" => "application/json"], + self::bodyWithoutStringConversion('{"id":"cus_123"}') + )])->getCustomersClient()->get("cus_123"); + + $this->assertSame("cus_123", $result["id"]); + } + + /** + * @test + */ + public function tokenBodiesAreReadWithoutTheirStringConversion() + { + $builder = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([ + new Response(200, [], self::bodyWithoutStringConversion( + '{"access_token":"' . self::ACCESS_TOKEN . '","expires_in":3600}' + )) + ])) + ->logger($this->logger()); + $this->assertInstanceOf("Checkout\\CheckoutApi", $builder->build()); + + $failing = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([ + new Response(400, [], self::bodyWithoutStringConversion('{"error":"invalid_client"}')) + ])) + ->logger($this->logger()); + try { + $failing->build(); + $this->fail("expected an exception"); + } catch (CheckoutException $e) { + $this->assertSame("OAuth token request failed with status 400 (invalid_client)", $e->getMessage()); + } + } + + /** + * A stream of a PSR-7 library without return types may give an object instead of text: it is + * treated as no body, without converting it. + * + * @test + */ + public function bodiesThatAreNotTextAreNotConverted() + { + if (PHP_VERSION_ID >= 70000 + && (new \ReflectionMethod(FnStream::class, "getContents"))->hasReturnType()) { + $this->markTestSkipped("streams of this PSR-7 version always give text"); + } + $e = $this->failedCustomersCall(function (RequestInterface $request) { + $response = new Response(401, [], ErrorHandlingTest::bodyThatIsNotText()); + throw new RequestException("failed", $request, $response); + }); + $this->assertSame("The API response status code (401) does not indicate success.", $e->getMessage()); + $this->assertSame([], $e->error_details); + + foreach (["application/json", "text/csv"] as $type) { + $result = $this->staticKeysApi([new Response(200, ["Content-Type" => $type], self::bodyThatIsNotText())]) + ->getCustomersClient()->get("cus_123"); + $this->assertSame(["http_metadata"], array_keys($result), $type); + } + + $builder = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([new Response(200, [], self::bodyThatIsNotText())])) + ->logger($this->logger()); + try { + $builder->build(); + $this->fail("expected an exception"); + } catch (CheckoutAuthorizationException $e) { + $this->assertSame("The authorization server returned an invalid access token response", $e->getMessage()); + } + } + + /** + * @test + */ + public function contentTypeThatIsNotTextIsNotConverted() + { + $response = Mockery::mock(Response::class, [200, [], '{"id":"cus_123"}'])->makePartial(); + $response->shouldReceive("getHeader")->with("Content-Type")->andReturn([new ErrorHandlingThrowingText()]); + + $result = $this->staticKeysApi([$response])->getCustomersClient()->get("cus_123"); + + $this->assertSame("cus_123", $result["id"]); + } + + /** + * @return FnStream a body whose getContents() gives an object whose string conversion throws + */ + public static function bodyThatIsNotText() + { + return FnStream::decorate(Utils::streamFor("{}"), [ + "getContents" => function () { + return new ErrorHandlingThrowingText(); + }, + "__toString" => function () { + return "{}"; + }, + ]); + } + + /** + * @param string $text + * @return FnStream a body whose getContents() works and whose string conversion throws + */ + public static function bodyWithoutStringConversion($text) + { + return FnStream::decorate(Utils::streamFor($text), [ + "__toString" => function () { + throw new \RuntimeException("string conversion"); + }, + ]); + } + + /** + * @param callable $handler + * @return CheckoutApiException the error of a customers call answered by the handler + */ + private function failedCustomersCall(callable $handler) + { + $error = null; + try { + $this->staticKeysApi([$handler])->getCustomersClient()->get("cus_123"); + } catch (CheckoutApiException $e) { + $error = $e; + } + // PHPUnit 5.7 does not declare fail() as never returning, so the method returns here. + $this->assertInstanceOf(CheckoutApiException::class, $error, "expected an exception"); + return $error; + } + + /** + * @test + */ + public function uploadLogLineNamesOnlyThePath() + { + $directory = sys_get_temp_dir() . "/upload-" . uniqid(); + mkdir($directory); + $file = $directory . "/evidence-" . self::UPLOAD_NAME . ".pdf"; + file_put_contents($file, "%PDF-1.4"); + $apiClient = new ApiClient(new CheckoutConfiguration( + $this->createMock(SdkCredentialsInterface::class), + Environment::sandbox(), + $this->httpClient([new Response(200, [], '{"id":"file_123"}')]), + $this->logger() + )); + $request = new FileRequest(); + $request->file = $file; + $request->purpose = "dispute_evidence"; + + try { + $apiClient->submitFile("files", $request, new SdkAuthorization(PlatformType::$default, self::SECRET_KEY)); + } finally { + unlink($file); + rmdir($directory); + } + + $messages = array_map(function ($record) { + return $record["message"]; + }, $this->logs->getRecords()); + $this->assertSame(["POST files"], $messages); + } + + /** + * @test + */ + public function responseHeadersAreKeptWithoutCookies() + { + $customers = $this->staticKeysApi([new Response(422, [ + "Cko-Request-Id" => "req_123", + "Set-Cookie" => "session=" . self::RESPONSE_COOKIE, + "set-cookie2" => "legacy=" . self::RESPONSE_COOKIE, + ], '{"error_type":"request_invalid"}')])->getCustomersClient(); + + try { + $customers->get("cus_123"); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + $headers = array_change_key_case($e->http_metadata->getHeaders(), CASE_LOWER); + $this->assertSame(["req_123"], $headers["cko-request-id"]); + $this->assertArrayNotHasKey("set-cookie", $headers); + $this->assertArrayNotHasKey("set-cookie2", $headers); + $this->assertSame(["error_type" => "request_invalid"], $e->error_details); + } + } + + /** + * @test + */ + public function failureOfAnAnonymousClassIsNamedWithoutItsFile() + { + if (PHP_VERSION_ID < 70000) { + $this->markTestSkipped("anonymous classes need PHP 7.0"); + } + $sessions = $this->staticKeysApi([ + function () { + // Declared at run time through eval, so that this file still parses on PHP 5.6, + // which has no anonymous classes. + throw eval('return new class ("failed") extends \RuntimeException {};'); + } + ])->getSessionsClient(); + + try { + $sessions->getSessionDetails("sid_123", self::SESSION_SECRET); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + // PHP 8.0 names an anonymous class after its parent; PHP 7 names it class@anonymous. + $this->assertSame( + PHP_VERSION_ID >= 80000 ? "RuntimeException@anonymous" : "class@anonymous", + $e->getMessage() + ); + } + } + + /** + * @test + */ + public function authorizationTypeErrorNamesOnlyKnownTypes() + { + $this->assertSame( + "Operation requires oauth authorization type", + CheckoutAuthorizationException::invalidAuthorization(AuthorizationType::$oAuth)->getMessage() + ); + $this->assertSame( + "Operation requires a supported authorization type", + CheckoutAuthorizationException::invalidAuthorization("Bearer " . self::SECRET_KEY)->getMessage() + ); + } + + /** + * @test + * @dataProvider tokenFailureMessages + */ + public function oauthTokenFailureMessageNamesTheStatusAndTheStandardErrorCode($response, $expected) + { + $builder = CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([$response])) + ->logger($this->logger()); + + try { + $builder->build(); + $this->fail("expected an exception"); + } catch (CheckoutException $e) { + $this->assertSame($expected, $e->getMessage()); + } + } + + public static function tokenFailureMessages() + { + return [ + "standard error code" => [ + new Response(400, [], '{"error":"invalid_client"}'), + "OAuth token request failed with status 400 (invalid_client)", + ], + "other error value" => [ + new Response(400, [], '{"error":"zqcsecret-0123456789abcdef"}'), + "OAuth token request failed with status 400", + ], + "no JSON" => [new Response(503, [], "unavailable"), "OAuth token request failed with status 503"], + "unreachable" => [ + new ConnectException("Connection refused", new Request("POST", "https://x"), null, ["errno" => 7]), + "OAuth token request failed: GuzzleHttp\\Exception\\ConnectException (cURL error 7)", + ], + ]; + } + + /** + * Every parameter of the kinds listed below carries the attribute. Reads the attribute by + * name, so it runs from PHP 8.0, where attributes can be read. + * + * @test + */ + public function everySensitiveParameterIsMarked() + { + if (PHP_VERSION_ID < 80000) { + $this->markTestSkipped("attributes can be read from PHP 8.0"); + } + $carrierTypes = [ + "Checkout\\SdkAuthorization", + "Checkout\\SdkCredentialsInterface", + "Checkout\\OAuthAccessToken", + "GuzzleHttp\\Exception\\RequestException", + "Throwable", + "Checkout\\Issuing\\Cards\\Enrollment\\ThreeDSEnrollmentRequest", + "Checkout\\Issuing\\Cards\\Enrollment\\UpdateThreeDSEnrollmentRequest", + "Checkout\\Workflows\\CreateWorkflowRequest", + "Checkout\\Workflows\\UpdateWorkflowRequest", + "Checkout\\Workflows\\Actions\\WorkflowActionRequest", + "Checkout\\Webhooks\\Previous\\WebhookRequest", + ]; + // Classes that only travel inside one of the carriers above. + $nested = [ + "Checkout\\Issuing\\Cards\\Enrollment\\SecurityPair", + "Checkout\\Workflows\\Actions\\WebhookSignature", + ]; + // Classes whose field of the same name is not a credential: payment data (wallet token + // signatures), risk data key/value pairs, the If-Match header and card lifetimes. + $notCredentials = [ + "Checkout\\Tokens\\ApplePayTokenData", + "Checkout\\Tokens\\GooglePayTokenData", + "Checkout\\Payments\\PartnerCustomerRiskData", + "Checkout\\Payments\\Contexts\\PaymentContextsPartnerCustomerRiskData", + "Checkout\\Accounts\\UpdatePaymentInstrumentRequest", + "Checkout\\Issuing\\Cards\\Create\\CardLifetime", + ]; + // Payment data (card security codes, PINs, one-time codes): left as they are on purpose, + // the hardening covers credentials. Listed so that a new class is classified, not missed. + $paymentData = [ + "Checkout\\Payments\\Previous\\Source\\RequestCardSource", + "Checkout\\Payments\\Previous\\Source\\RequestDLocalSource", + "Checkout\\Payments\\Previous\\Source\\RequestIdSource", + "Checkout\\Payments\\Previous\\Source\\RequestNetworkTokenSource", + "Checkout\\Payments\\Request\\Source\\RequestCardSource", + "Checkout\\Payments\\Request\\Source\\RequestIdSource", + "Checkout\\Payments\\Request\\Source\\RequestNetworkTokenSource", + "Checkout\\Risk\\Source\\IdSourcePrism", + "Checkout\\Tokens\\CardTokenRequest", + ]; + // Configuration objects, in the methods that build the HTTP client. + $configurationTypes = ["Checkout\\CheckoutConfiguration", "Checkout\\HttpClientBuilderInterface"]; + // Parameters whose name does not say what they carry. Parameters that receive a failure + // or a response have no type on this line (PHP 5.6 has no Throwable): a failure is found + // by its documented type, a response is listed here. + $byPosition = [ + "Checkout\\AbstractStaticKeysCheckoutSdkBuilder::validateSecretKey" => ["key"], + "Checkout\\AbstractStaticKeysCheckoutSdkBuilder::validKey" => ["key"], + "Checkout\\SdkAuthorization::__construct" => ["credential"], + "Checkout\\SdkAuthorization::asText" => ["value"], + "Checkout\\CheckoutUtils::statusOf" => ["response"], + "Checkout\\CheckoutUtils::bodyOf" => ["response"], + "Checkout\\CheckoutUtils::contentsOf" => ["stream"], + "Checkout\\CheckoutApiException::metadataWithoutCookies" => ["response"], + "Checkout\\CheckoutAuthorizationException::invalidAuthorization" => ["authorizationType"], + "Checkout\\ApiClient::post" => ["body"], + "Checkout\\ApiClient::put" => ["body"], + "Checkout\\ApiClient::patch" => ["body"], + "Checkout\\ApiClient::invoke" => ["body"], + ]; + // The ticket names these; each one is checked even if the rules above change. + $named = [ + "Checkout\\OAuthSdkCredentials::__construct" => ["clientSecret"], + "Checkout\\OAuthSdkCredentials::init" => ["clientSecret"], + "Checkout\\CheckoutOAuthSdkBuilder::clientCredentials" => ["clientSecret"], + "Checkout\\AbstractStaticKeysSdkCredentials::__construct" => ["secretKey"], + "Checkout\\StaticKeysSdkCredentials::__construct" => ["secretKey"], + "Checkout\\Previous\\PreviousStaticKeysSdkCredentials::__construct" => ["secretKey"], + "Checkout\\CheckoutStaticKeysSdkBuilder::secretKey" => ["secretKey"], + "Checkout\\Previous\\CheckoutStaticKeysPreviousSdkBuilder::secretKey" => ["secretKey"], + "Checkout\\Sessions\\SessionsClient::getSessionDetails" => ["sessionSecret"], + "Checkout\\Sessions\\SessionsClient::updateSession" => ["sessionSecret"], + "Checkout\\Sessions\\SessionsClient::completeSession" => ["sessionSecret"], + "Checkout\\Sessions\\SessionsClient::updateThreeDsMethodCompletionIndicator" => ["sessionSecret"], + "Checkout\\Sessions\\SessionSecretSdkCredentials::__construct" => ["secret"], + "Checkout\\OAuthSdkCredentials::tokenFailureMessage" => ["failure"], + ]; + + $unmarked = []; + $checked = []; + $buildsHttpClient = []; + foreach ($this->libraryMethods() as $method) { + $id = $method->getDeclaringClass()->getName() . "::" . $method->getName(); + $httpClientBuilt = preg_match( + '/ApiClient\(|->getClient\(\)|new OAuthSdkCredentials\(/', + $this->sourceOf($method) + ) === 1; + if ($httpClientBuilt) { + $buildsHttpClient[] = $id; + } + $documentedFailures = $this->documentedFailureParameters($method); + foreach ($method->getParameters() as $parameter) { + $required = $this->carriesCredentialByName($parameter) + || $this->hasType($parameter, $carrierTypes) + || in_array($parameter->getName(), $documentedFailures, true) + || ($httpClientBuilt && $this->hasType($parameter, $configurationTypes)) + || (isset($byPosition[$id]) && in_array($parameter->getName(), $byPosition[$id], true)) + || (isset($named[$id]) && in_array($parameter->getName(), $named[$id], true)); + if (!$required) { + continue; + } + $checked[$id . " $" . $parameter->getName()] = true; + if (empty($parameter->getAttributes("SensitiveParameter"))) { + $unmarked[] = $id . " $" . $parameter->getName(); + } + } + } + + foreach (array_merge_recursive($byPosition, $named) as $id => $names) { + foreach ($names as $name) { + $this->assertArrayHasKey($id . " $" . $name, $checked, "no such parameter: $id $$name"); + } + } + foreach (["Checkout\\CheckoutUtils::describeFailure", "Checkout\\CheckoutUtils::responseOf"] as $id) { + $this->assertArrayHasKey($id . " $" . "failure", $checked, "not seen as receiving a failure: $id"); + } + foreach (["Checkout\\ApiClient::__construct", "Checkout\\CheckoutApi::__construct"] as $id) { + $this->assertContains($id, $buildsHttpClient, "not seen as building the HTTP client: $id"); + } + $uncovered = []; + foreach ($this->libraryClasses() as $class) { + $secretFields = array_filter($class->getProperties(\ReflectionProperty::IS_PUBLIC), function ($property) { + return !$property->isStatic() && preg_match( + '/^(password|security_pair|client_secret|secret|secret_key|encryption_key|signature|key|headers|raw' + . '|value|pin|cvv)$/', + $property->getName() + ) === 1; + }); + $listed = array_merge($nested, $notCredentials, $paymentData); + if (empty($secretFields) || in_array($class->getName(), $listed, true)) { + continue; + } + $covered = false; + foreach ($carrierTypes as $carrier) { + $covered = $covered || $class->getName() === $carrier || is_subclass_of($class->getName(), $carrier); + } + if (!$covered) { + $uncovered[] = $class->getName(); + } + } + $this->assertSame([], $uncovered, "classes with sensitive fields that are not listed"); + $this->assertSame([], $unmarked, "parameters without the attribute"); + } + + /** + * @param ReflectionParameter $parameter + * @return bool true for a name that says the value is a secret or a token, and not an id, a + * type, a pattern, a URI or a request object named after one + */ + private function carriesCredentialByName(ReflectionParameter $parameter) + { + $name = $parameter->getName(); + return preg_match('/secret|token|credential|password|^authorization$/i', $name) === 1 + && preg_match('/(Id|Type|Pattern|Uri|Request)$/', $name) !== 1; + } + + /** + * @param ReflectionMethod $method + * @return string[] names of the parameters documented as a failure (Throwable, or Exception + * and its subclasses): on this line they cannot be typed + */ + private function documentedFailureParameters(ReflectionMethod $method) + { + $doc = (string)$method->getDocComment(); + preg_match_all('/@param\s+(\S+)\s+\$(\w+)/', $doc, $params, PREG_SET_ORDER); + $names = []; + foreach ($params as $param) { + if (preg_match('/(^|[|\\\\])(Throwable|\w*Exception)(\||$)/', $param[1]) === 1) { + $names[] = $param[2]; + } + } + return $names; + } + + private function hasType(ReflectionParameter $parameter, array $types) + { + $type = $parameter->getType(); + if ($type === null || !method_exists($type, "getName")) { + return false; + } + foreach ($types as $carrier) { + if ($type->getName() === $carrier || is_subclass_of($type->getName(), $carrier)) { + return true; + } + } + return false; + } + + private function sourceOf(ReflectionMethod $method) + { + return implode("", array_slice( + file($method->getFileName()), + $method->getStartLine() - 1, + $method->getEndLine() - $method->getStartLine() + 1 + )); + } + + /** + * @return ReflectionMethod[] every method declared in lib/ + */ + private function libraryMethods() + { + $methods = []; + foreach ($this->libraryClasses() as $reflection) { + foreach ($reflection->getMethods() as $method) { + if ($method->getDeclaringClass()->getName() === $reflection->getName()) { + $methods[] = $method; + } + } + } + $this->assertNotEmpty($methods, "lib/ scan found no methods"); + return $methods; + } + + /** + * @return ReflectionClass[] every class, interface and trait declared in lib/ + */ + private function libraryClasses() + { + $root = realpath(__DIR__ . "/../../../lib"); + $classes = []; + $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($root)); + foreach ($files as $file) { + if ($file->getExtension() !== "php") { + continue; + } + $source = file_get_contents($file->getPathname()); + if (!preg_match('/^namespace\s+([^;]+);/m', $source, $namespace) + || !preg_match( + '/^(?:(?:abstract|final|readonly)\s+)*(?:class|interface|trait|enum)\s+(\w+)/m', + $source, + $class + )) { + continue; + } + $classes[] = new ReflectionClass($namespace[1] . "\\" . $class[1]); + } + return $classes; + } + + public static function apiFailures() + { + $cases = [ + "status 401" => [new Response(401, [], "")], + "status 400 error page" => [self::errorPage(400, "", "")], + "status 401 setting a cookie" => [ + new Response(401, ["Set-Cookie" => "session=" . self::RESPONSE_COOKIE . "; Secure"], "") + ], + "failure with a long message" => [self::failingHandler("plain")], + "SDK exception type from the HTTP stack" => [self::failingHandler("sdk")], + "SDK exception factory from the HTTP stack" => [self::failingHandler("sdk factory")], + "failure whose response cannot be read" => [self::failingHandler("unreadable response")], + "failure whose body cannot be read" => [self::failingHandler("unreadable body")], + "failure with a text code" => [self::failingHandler("text code")], + "failure with an unusual context" => [self::failingHandler("object context")], + "failure whose context cannot be read" => [self::failingHandler("failing context")], + "unreachable" => [new ConnectException("Connection refused", new Request("GET", "https://x"))], + ]; + if (PHP_VERSION_ID >= 70000) { + $cases["error in the HTTP client"] = [self::errorInTheHttpClient()]; + } + return $cases; + } + + /** + * @param int $status + * @param string $before + * @param string $after + * @return callable a handler that answers with a non-JSON page made of the request headers and + * body + */ + private static function errorPage($status, $before = "", $after = "") + { + return function (RequestInterface $request) use ($status, $before, $after) { + $page = $before . (string)$request->getBody() . " " . json_encode($request->getHeaders()) . $after; + return new Response($status, ["Content-Type" => "text/html"], $page); + }; + } + + /** + * @param int $status + * @return callable a handler that answers with a response whose body fails when read, with a + * message made of the request headers and body. Before PHP 7.4 a string conversion cannot + * throw, so there it gives a body that is not JSON. + */ + private static function unreadableBody($status) + { + return function (RequestInterface $request) use ($status) { + $message = "failed " . json_encode($request->getHeaders()) . " " . (string)$request->getBody(); + $fail = function () use ($message) { + throw new \RuntimeException($message); + }; + $toString = PHP_VERSION_ID >= 70400 ? $fail : function () { + return "{"; + }; + $body = FnStream::decorate(Utils::streamFor("{}"), [ + "__toString" => $toString, "getContents" => $fail, "read" => $fail, + ]); + return new Response($status, ["Content-Type" => "application/json"], $body); + }; + } + + /** + * @param string $kind "plain" (a RuntimeException), "sdk" (a CheckoutException subclass), "sdk + * factory" (an SDK exception built by an SDK factory method), "unreadable response" or + * "unreadable body" (a RequestException whose response or body cannot be read), + * "text code" (a RequestException whose code is text), "object context" or "failing + * context" (a failure whose handler context is not an array or cannot be read) + * @return callable a handler that fails with a message made of the request headers and body + */ + private static function failingHandler($kind) + { + return function (RequestInterface $request) use ($kind) { + $message = "failed " . json_encode($request->getHeaders()) . " " . (string)$request->getBody(); + switch ($kind) { + case "sdk": + throw new ErrorHandlingForeignException($message); + case "sdk factory": + throw CheckoutAuthorizationException::invalidAuthorization($message); + case "unreadable response": + $failure = Mockery::mock(RequestException::class, [$message, $request])->makePartial(); + $failure->shouldReceive("getResponse")->andThrow(new \RuntimeException("no response")); + throw $failure; + case "text code": + throw new ErrorHandlingTextCodeException($message, $request); + case "unreadable body": + $unreadable = ErrorHandlingTest::unreadableBody(500); + throw new RequestException($message, $request, $unreadable($request)); + case "object context": + throw new ErrorHandlingObjectContextException($message); + case "failing context": + throw new ErrorHandlingFailingContextException($message); + default: + throw new \RuntimeException($message); + } + }; + } + + /** + * @return callable a handler that raises an Error while the HTTP client frames are on the + * stack (PHP 7.0 and later) + */ + private static function errorInTheHttpClient() + { + return function () { + throw new \TypeError("Unsupported operand types"); + }; + } + + private static function caseNames(array $cases) + { + $names = []; + foreach (array_keys($cases) as $name) { + $names[$name] = [$name]; + } + return $names; + } + + /** + * Reads the value itself, so the arguments of the test methods hold none. + */ + public static function callSessions($sessions, $method) + { + $secret = self::SESSION_SECRET; + switch ($method) { + case "updateSession": + $sessions->updateSession("sid_123", new BrowserSession(), $secret); + break; + case "updateThreeDsMethodCompletionIndicator": + $sessions->updateThreeDsMethodCompletionIndicator( + "sid_123", + new ThreeDsMethodCompletionRequest(), + $secret + ); + break; + default: + $sessions->$method("sid_123", $secret); + } + } + + /** + * Builds each request with its sensitive fields set, so the arguments of the test methods hold + * none. + */ + public static function callWithSensitiveFields(ErrorHandlingTest $test, $method, array $responses) + { + $signature = new WebhookSignature(); + $signature->method = "HMACSHA256"; + $signature->key = self::SIGNING_KEY; + $action = new WebhookWorkflowActionRequest(); + $action->url = "https://example.com/webhooks"; + $action->headers = ["Authorization" => self::SIGNING_KEY]; + $action->signature = $signature; + $pair = new SecurityPair(); + $pair->question = "Who?"; + $pair->answer = self::ENROLLMENT_SECRET; + $webhook = new WebhookRequest(); + $webhook->url = "https://example.com/webhooks"; + $webhook->headers = ["Authorization" => self::SIGNING_KEY]; + switch ($method) { + case "enrollThreeDS": + $request = new PasswordThreeDSEnrollmentRequest(); + $request->password = self::ENROLLMENT_SECRET; + $test->staticKeysApi($responses)->getIssuingClient()->enrollThreeDS("crd_123", $request); + break; + case "updateThreeDSEnrollment": + $request = new UpdateThreeDSEnrollmentRequest(); + $request->password = self::ENROLLMENT_SECRET; + $request->security_pair = $pair; + $test->staticKeysApi($responses)->getIssuingClient()->updateThreeDSEnrollment("crd_123", $request); + break; + case "createWorkflow": + $request = new CreateWorkflowRequest(); + $request->actions = [$action]; + $test->staticKeysApi($responses)->getWorkflowsClient()->createWorkflow($request); + break; + case "updateWorkflow": + $request = new UpdateWorkflowRequest(); + $request->actions = [$action]; + $test->staticKeysApi($responses)->getWorkflowsClient()->updateWorkflow("wf_123", $request); + break; + case "addWorkflowAction": + $test->staticKeysApi($responses)->getWorkflowsClient()->addWorkflowAction("wf_123", $action); + break; + case "updateWorkflowAction": + $test->staticKeysApi($responses)->getWorkflowsClient() + ->updateWorkflowAction("wf_123", "wfa_123", $action); + break; + default: + $webhooks = $test->previousApi($responses)->getWebhooksClient(); + if ($method === "registerWebhook") { + $webhooks->registerWebhook($webhook); + } else { + $webhooks->$method("wh_123", $webhook); + } + } + } + + /** + * @param array $responses + * @param mixed $secretKey + */ + public function staticKeysApi(array $responses, $secretKey = self::SECRET_KEY) + { + return CheckoutSdk::builder()->staticKeys() + ->secretKey($secretKey) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient($responses)) + ->logger($this->logger()) + ->build(); + } + + public function previousApi(array $responses) + { + return CheckoutSdk::builder()->previous()->staticKeys() + ->secretKey(self::PREVIOUS_SECRET_KEY) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient($responses)) + ->logger($this->logger()) + ->build(); + } + + private function logger() + { + $logger = new Logger("checkout-sdk-test-php"); + $logger->pushHandler($this->logs); + return $logger; + } + + private function httpClient(array $queue) + { + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method("getClient")->willReturn(new Client([ + "handler" => HandlerStack::create(new MockHandler($queue)), + "allow_redirects" => false, + ])); + return $builder; + } + + /** + * @param int $working calls of getClient() that succeed before it throws + * @param array $queue responses of the client those calls return + */ + private function failingHttpClientBuilder($working, array $queue = []) + { + $client = new Client(["handler" => HandlerStack::create(new MockHandler($queue))]); + $calls = new \ArrayObject([0]); + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method("getClient")->willReturnCallback(function () use ($client, $working, $calls) { + if ($calls[0]++ >= $working) { + // Created inside the SDK call, as a real client builder would. + throw new \RuntimeException("no client"); + } + return $client; + }); + return $builder; + } + + /** + * Runs $call, expects a CheckoutApiException, and checks the error and the log line. The HTTP + * client of this line raises transport failures as a RequestException without a response + * (Guzzle 6) or as an exception of their own (Guzzle 7): the log line names the failure on + * both, the message from Guzzle 7, as before for Guzzle 6. + * + * @param callable $call + * @param string $description the expected description of the failure + */ + private function assertTransportFailure(callable $call, $description) + { + try { + $call(); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + $expected = is_subclass_of(ConnectException::class, RequestException::class) + ? "The API response status code (0) does not indicate success." + : $description; + $this->assertSame($expected, $e->getMessage()); + } + $messages = []; + foreach ($this->logs->getRecords() as $record) { + $messages[] = $record["message"]; + } + $this->assertSame(" error: " . $description, strstr(end($messages), " error: ")); + } + + /** + * Runs $call, expects it to throw $expected, and checks the error and the log. The message, + * the previous exceptions, the public properties and the log are checked on every PHP version; + * the string form and the trace from PHP 8.2. + * + * @param callable $call + * @param string $expected + */ + private function assertErrorsClean(callable $call, $expected) + { + try { + $call(); + } catch (\Exception $e) { + $this->assertFailureClean($e, $expected); + return; + } catch (\Throwable $e) { + $this->assertFailureClean($e, $expected); + return; + } + $this->fail("expected " . $expected); + } + + /** + * @param \Throwable|\Exception $e + * @param string $expected + */ + private function assertFailureClean($e, $expected) + { + $this->assertInstanceOf($expected, $e, get_class($e) . ": " . $e->getMessage()); + $renderings = []; + $seen = []; + for ($current = $e; $current !== null; $current = $current->getPrevious()) { + $class = get_class($current); + $renderings[$class . " message"] = $current->getMessage(); + $strings = []; + $this->collectStrings(get_object_vars($current), $seen, $strings, 0); + $renderings[$class . " public properties"] = implode("\n", $strings); + if (PHP_VERSION_ID < 80200) { + continue; + } + $renderings[$class . " string"] = (string)$current; + $renderings[$class . " trace as string"] = $current->getTraceAsString(); + $strings = []; + foreach ($current->getTrace() as $frame) { + $frameClass = isset($frame["class"]) ? $frame["class"] : ""; + if (strpos($frameClass, "PHPUnit\\") === 0 || $frameClass === self::class) { + continue; + } + $this->collectStrings(isset($frame["args"]) ? $frame["args"] : [], $seen, $strings, 0); + } + $renderings[$class . " trace arguments"] = implode("\n", $strings); + } + foreach ($this->logs->getRecords() as $i => $record) { + $renderings["log " . $i] = print_r($record, true); + } + foreach ($renderings as $where => $text) { + foreach (self::TAGS as $tag) { + $this->assertTrue(strpos($text, $tag) === false, "credential in " . $where); + } + } + } + + /** + * Collects every string reachable from $value, private and protected properties and message + * bodies included (what a consumer that dumps frame arguments would print). Test framework + * objects are skipped. + */ + private function collectStrings($value, array &$seen, array &$strings, $depth) + { + if ($depth > 10) { + return; + } + if (is_string($value)) { + $strings[] = $value; + return; + } + if (is_object($value)) { + if (isset($seen[spl_object_hash($value)]) + || preg_match('/^(PHPUnit|Mockery|SebastianBergmann|Monolog|Closure)/', get_class($value)) === 1) { + return; + } + $seen[spl_object_hash($value)] = true; + if ($value instanceof MessageInterface) { + $strings[] = print_r($value->getHeaders(), true); + try { + $strings[] = (string)$value->getBody(); + } catch (\Exception $unreadable) { + $strings[] = ""; + } + } + $value = (array)$value; + } + if (is_array($value)) { + foreach ($value as $key => $item) { + $strings[] = (string)$key; + $this->collectStrings($item, $seen, $strings, $depth + 1); + } + } + } +} diff --git a/test/Checkout/Tests/ErrorHandlingTextCodeException.php b/test/Checkout/Tests/ErrorHandlingTextCodeException.php new file mode 100644 index 00000000..7aee5930 --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingTextCodeException.php @@ -0,0 +1,18 @@ +code = ErrorHandlingTest::FAILURE_CODE; + } +} diff --git a/test/Checkout/Tests/ErrorHandlingThrowingText.php b/test/Checkout/Tests/ErrorHandlingThrowingText.php new file mode 100644 index 00000000..85098e3d --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingThrowingText.php @@ -0,0 +1,14 @@ +build(); $this->fail("shouldn't get here"); } catch (Exception $e) { - $this->assertEquals("Client error: `POST https://access.sandbox.checkout.com/connect/token` resulted in a `400 Bad Request` response:\n{\"error\":\"invalid_client\"}\n", $e->getMessage()); + $this->assertEquals("OAuth token request failed with status 400 (invalid_client)", $e->getMessage()); } } @@ -94,7 +94,10 @@ public function shouldFailInitAuthorizationCustomFakeAuthorizationUri() ->build(); $this->fail("shouldn't get here"); } catch (Exception $e) { - $this->assertTrue(strpos($e->getMessage(), "cURL error 6: Could not resolve host: test.checkout.com") !== false); + $this->assertEquals( + "OAuth token request failed: GuzzleHttp\\Exception\\ConnectException (cURL error 6)", + $e->getMessage() + ); } } diff --git a/test/Checkout/Tests/SandboxTestFixture.php b/test/Checkout/Tests/SandboxTestFixture.php index ecb4ebfa..7555998d 100644 --- a/test/Checkout/Tests/SandboxTestFixture.php +++ b/test/Checkout/Tests/SandboxTestFixture.php @@ -190,11 +190,12 @@ protected function getAccountHolder() /** * @param callable $func - * @param callable|null $predicate + * @param callable|null $predicate untyped: PHP 5.6 cannot declare a nullable type, and an + * implicitly nullable one is deprecated from PHP 8.4 * @param int $timeout * @return mixed */ - protected function retriable(callable $func, callable $predicate = null, $timeout = 2) + protected function retriable(callable $func, $predicate = null, $timeout = 2) { $currentAttempt = 1; $maxAttempts = 10; From bc0dbafb4af26a525869bf9505ecc5af47a7431f Mon Sep 17 00:00:00 2001 From: david ruiz Date: Fri, 4 Dec 2026 09:58:57 +0100 Subject: [PATCH 2/4] test: OAuth payment test no longer sends marketplace --- test/Checkout/Tests/OAuthIntegrationTest.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/Checkout/Tests/OAuthIntegrationTest.php b/test/Checkout/Tests/OAuthIntegrationTest.php index 39b5c8a5..2efb01b3 100644 --- a/test/Checkout/Tests/OAuthIntegrationTest.php +++ b/test/Checkout/Tests/OAuthIntegrationTest.php @@ -5,7 +5,6 @@ use Checkout\CheckoutApiException; use Checkout\CheckoutSdk; use Checkout\Common\Currency; -use Checkout\Common\MarketplaceData; use Checkout\Environment; use Checkout\Payments\Request\PaymentRequest; use Checkout\Payments\Request\Source\RequestCardSource; @@ -44,9 +43,6 @@ public function shouldMakePaymentWithOAuth() $paymentIndividualSender->last_name = "Test"; $paymentIndividualSender->address = $this->getAddress(); - $marketplace = new MarketplaceData(); - $marketplace->sub_entity_id = "ent_ocw5i74vowfg2edpy66izhts2u"; - $paymentRequest = new PaymentRequest(); $paymentRequest->source = $requestCardSource; $paymentRequest->capture = false; @@ -54,7 +50,6 @@ public function shouldMakePaymentWithOAuth() $paymentRequest->amount = 10; $paymentRequest->currency = Currency::$EUR; $paymentRequest->processing_channel_id = "pc_a6dabcfa2o3ejghb3sjuotdzzy"; - $paymentRequest->marketplace = $marketplace; $paymentRequest->sender = $paymentIndividualSender; $paymentResponse = $this->checkoutApi->getPaymentsClient()->requestPayment($paymentRequest); From 21d21b97b4d63e4dcd6b8bf65d7918287378c9c4 Mon Sep 17 00:00:00 2001 From: david ruiz Date: Fri, 4 Dec 2026 10:12:42 +0100 Subject: [PATCH 3/4] test: OAuth payment test allocates the amount to the sub-entity --- test/Checkout/Tests/OAuthIntegrationTest.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/Checkout/Tests/OAuthIntegrationTest.php b/test/Checkout/Tests/OAuthIntegrationTest.php index 2efb01b3..fd9c6f75 100644 --- a/test/Checkout/Tests/OAuthIntegrationTest.php +++ b/test/Checkout/Tests/OAuthIntegrationTest.php @@ -4,6 +4,7 @@ use Checkout\CheckoutApiException; use Checkout\CheckoutSdk; +use Checkout\Common\AmountAllocations; use Checkout\Common\Currency; use Checkout\Environment; use Checkout\Payments\Request\PaymentRequest; @@ -43,6 +44,13 @@ public function shouldMakePaymentWithOAuth() $paymentIndividualSender->last_name = "Test"; $paymentIndividualSender->address = $this->getAddress(); + // The OAuth client's entity must allocate the payment to a sub-entity; the sandbox refuses + // the former marketplace object (marketplace_not_supported) and a payment without an + // allocation (amount_allocations_required). + $allocation = new AmountAllocations(); + $allocation->id = "ent_ocw5i74vowfg2edpy66izhts2u"; + $allocation->amount = 10; + $paymentRequest = new PaymentRequest(); $paymentRequest->source = $requestCardSource; $paymentRequest->capture = false; @@ -51,6 +59,7 @@ public function shouldMakePaymentWithOAuth() $paymentRequest->currency = Currency::$EUR; $paymentRequest->processing_channel_id = "pc_a6dabcfa2o3ejghb3sjuotdzzy"; $paymentRequest->sender = $paymentIndividualSender; + $paymentRequest->amount_allocations = array($allocation); $paymentResponse = $this->checkoutApi->getPaymentsClient()->requestPayment($paymentRequest); From f0bb929da1fd988ffe7812d959f4d33022d85c4b Mon Sep 17 00:00:00 2001 From: david ruiz Date: Fri, 4 Dec 2026 16:21:48 +0100 Subject: [PATCH 4/4] fix(client): review follow-ups --- lib/Checkout/ApiClient.php | 13 ++++++++----- lib/Checkout/CheckoutApiException.php | 8 +++++--- lib/Checkout/CheckoutUtils.php | 6 ++++-- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/lib/Checkout/ApiClient.php b/lib/Checkout/ApiClient.php index 203b5286..4557a724 100644 --- a/lib/Checkout/ApiClient.php +++ b/lib/Checkout/ApiClient.php @@ -257,11 +257,12 @@ private function failure( #[\SensitiveParameter] $failure ) { - $this->logger->error($path . " error: " . CheckoutUtils::describeFailure($failure)); + $description = CheckoutUtils::describeFailure($failure); + $this->logger->error($path . " error: " . $description); if ($failure instanceof RequestException) { return CheckoutApiException::from($failure); } - return new CheckoutApiException(CheckoutUtils::describeFailure($failure)); + return new CheckoutApiException($description); } /** @@ -299,11 +300,13 @@ private function getHeaders( if (!empty($idempotencyKey)) { $headers["Cko-Idempotency-Key"] = $idempotencyKey; } - // Every header value, Authorization included, is checked here once. Anything but a clean - // "no match" (a PCRE error returns false) is refused. + // Every header value, Authorization included, is checked here once. A value that is not + // scalar is refused before the cast: below PHP 8, casting an object without __toString is + // a fatal error no catch can handle, and the HTTP client refuses objects and arrays anyway. + // Anything but a clean "no match" (a PCRE error returns false) is refused. foreach ($headers as $value) { foreach (is_array($value) ? $value : array($value) as $item) { - if (preg_match('/[\x00-\x08\x0A-\x1F\x7F]/', (string)$item) !== 0) { + if (!is_scalar($item) || preg_match('/[\x00-\x08\x0A-\x1F\x7F]/', (string)$item) !== 0) { throw new CheckoutArgumentException("Invalid header value"); } } diff --git a/lib/Checkout/CheckoutApiException.php b/lib/Checkout/CheckoutApiException.php index 1e3144de..26e01783 100644 --- a/lib/Checkout/CheckoutApiException.php +++ b/lib/Checkout/CheckoutApiException.php @@ -8,8 +8,9 @@ class CheckoutApiException extends CheckoutException { /** - * @var array|null the decoded JSON body of the response; an empty array when there is no - * response or its body cannot be read, null when the body is not JSON + * @var array|string|int|float|bool|null the decoded JSON body of the response, usually an + * array (a JSON scalar decodes to its value); an empty array when there is no response or + * its body cannot be read, null when the body is not JSON */ public $error_details; /** @@ -20,7 +21,8 @@ class CheckoutApiException extends CheckoutException /** * @param RequestException $requestException a failed request of the HTTP client - * @return CheckoutApiException with the status in its message (0 when there is none), the + * @return CheckoutApiException with the response status in its message, or the failure's own + * code when there is no readable response (0 for the HTTP client's own errors), the * response body in error_details and the response metadata in http_metadata */ public static function from( diff --git a/lib/Checkout/CheckoutUtils.php b/lib/Checkout/CheckoutUtils.php index 127a45db..8465f3f4 100644 --- a/lib/Checkout/CheckoutUtils.php +++ b/lib/Checkout/CheckoutUtils.php @@ -132,7 +132,8 @@ public static function statusOf( } /** - * The whole body of a response, read from the start. For internal use by the SDK. + * The body of a response: all of it when the stream is seekable, otherwise what remains + * unread. For internal use by the SDK. * * @internal * @param ResponseInterface|null $response the response to read, if any @@ -155,7 +156,8 @@ public static function bodyOf( } /** - * The whole text of a stream, read from the start. For internal use by the SDK. + * The text of a stream: all of it when the stream is seekable, otherwise what remains + * unread. For internal use by the SDK. * * Reads with rewind() and getContents(), not __toString(): an exception thrown inside * __toString() cannot be caught before PHP 7.4.