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 1647e4ee..017434e7 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,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 0bcaca4a..428a1306 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\Stream; use GuzzleHttp\Psr7\Response; @@ -17,8 +16,15 @@ class ApiClient private $logger; private $baseUri; - public function __construct(CheckoutConfiguration $configuration, ?string $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, + ?string $baseUri = null + ) { $this->configuration = $configuration; $this->client = $configuration->getHttpClientBuilder()->getClient(); $this->jsonSerializer = new JsonSerializer(); @@ -34,8 +40,11 @@ public function __construct(CheckoutConfiguration $configuration, ?string $baseU * @return array * @throws CheckoutApiException */ - public function get(string $path, SdkAuthorization $authorization): array - { + public function get( + string $path, + #[\SensitiveParameter] + SdkAuthorization $authorization + ): array { return $this->invoke("GET", $path, null, $authorization); } @@ -49,17 +58,13 @@ public function get(string $path, SdkAuthorization $authorization): array */ public function post( string $path, + #[\SensitiveParameter] $body, + #[\SensitiveParameter] SdkAuthorization $authorization, ?string $idempotencyKey = null ): array { - return $this->invoke( - "POST", - $path, - $body === null ? null : $this->jsonSerializer->serialize($body), - $authorization, - $idempotencyKey - ); + return $this->invoke("POST", $path, $body, $authorization, $idempotencyKey); } /** @@ -69,9 +74,14 @@ public function post( * @return array * @throws CheckoutApiException */ - public function put(string $path, $body, SdkAuthorization $authorization): array - { - return $this->invoke("PUT", $path, $this->jsonSerializer->serialize($body), $authorization); + public function put( + string $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization + ): array { + return $this->invoke("PUT", $path, $body, $authorization); } /** @@ -81,9 +91,14 @@ public function put(string $path, $body, SdkAuthorization $authorization): array * @return array * @throws CheckoutApiException */ - public function patch(string $path, $body, SdkAuthorization $authorization): array - { - return $this->invoke("PATCH", $path, $this->jsonSerializer->serialize($body), $authorization); + public function patch( + string $path, + #[\SensitiveParameter] + $body, + #[\SensitiveParameter] + SdkAuthorization $authorization + ): array { + return $this->invoke("PATCH", $path, $body, $authorization); } /** @@ -92,8 +107,11 @@ public function patch(string $path, $body, SdkAuthorization $authorization): arr * @return array * @throws CheckoutApiException */ - public function delete(string $path, SdkAuthorization $authorization): array - { + public function delete( + string $path, + #[\SensitiveParameter] + SdkAuthorization $authorization + ): array { return $this->invoke("DELETE", $path, null, $authorization); } @@ -108,6 +126,7 @@ public function delete(string $path, SdkAuthorization $authorization): array public function query( string $path, AbstractQueryFilter $body, + #[\SensitiveParameter] SdkAuthorization $authorization ): array { $this->logger->info("GET " . $path); @@ -128,6 +147,7 @@ public function query( public function submitFile( string $path, FileRequest $fileRequest, + #[\SensitiveParameter] SdkAuthorization $authorization ): array { return $this->submit($path, $fileRequest, $authorization, "file"); @@ -143,6 +163,7 @@ public function submitFile( public function submitFileFilesApi( string $path, FileRequest $fileRequest, + #[\SensitiveParameter] SdkAuthorization $authorization ): array { return $this->submit($path, $fileRequest, $authorization, "path"); @@ -159,11 +180,12 @@ public function submitFileFilesApi( private function submit( string $path, FileRequest $fileRequest, + #[\SensitiveParameter] SdkAuthorization $authorization, string $multipart ): array { try { - $this->logger->info("POST " . $path . " file: " . $fileRequest->file); + $this->logger->info("POST " . $path); $headers = $this->getHeaders($authorization, null, null); // Provide a stream with explicit size so Guzzle can set Content-Length correctly. @@ -189,45 +211,51 @@ private function submit( ] ]); return $this->getResponseContents($response); - } catch (Exception $e) { - $this->logger->error($path . " error: " . $e->getMessage()); + } catch (\Throwable $e) { + $description = CheckoutUtils::describeFailure($e); + $this->logger->error($path . " error: " . $description); if ($e instanceof RequestException) { throw CheckoutApiException::from($e); } - throw new CheckoutApiException($e); + throw new CheckoutApiException($description); } } /** * @param string $method * @param string $path - * @param mixed $body + * @param mixed $body request object, serialized to JSON here; null sends no body * @param SdkAuthorization $authorization * @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( string $method, string $path, + #[\SensitiveParameter] $body, + #[\SensitiveParameter] SdkAuthorization $authorization, ?string $idempotencyKey = null ): array { try { $this->logger->info($method . " " . $path); + $json = $body === null ? null : $this->jsonSerializer->serialize($body); $headers = $this->getHeaders($authorization, "application/json", $idempotencyKey); $response = $this->client->request($method, $this->getRequestUrl($path), [ - "body" => $body, + "body" => $json, "headers" => $headers ]); return $this->getResponseContents($response); - } catch (Exception $e) { - $this->logger->error($path . " error: " . $e->getMessage()); + } catch (\Throwable $e) { + $description = CheckoutUtils::describeFailure($e); + $this->logger->error($path . " error: " . $description); if ($e instanceof RequestException) { throw CheckoutApiException::from($e); } - throw new CheckoutApiException($e); + throw new CheckoutApiException($description); } } @@ -241,9 +269,12 @@ private function getRequestUrl(string $path): string * @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( + #[\SensitiveParameter] SdkAuthorization $authorization, ?string $contentType, ?string $idempotencyKey @@ -259,6 +290,16 @@ 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. + foreach ($headers as $value) { + foreach (is_array($value) ? $value : [$value] as $item) { + if (preg_match('/[\x00-\x08\x0A-\x1F\x7F]/', (string)$item) !== 0) { + throw new CheckoutArgumentException("Invalid header value"); + } + } + } return $headers; } @@ -269,10 +310,12 @@ private function getHeaders( private function getResponseContents(Response $response): array { $contentType = $response->getHeader("Content-Type"); - if (in_array("text/csv", $contentType)) { + // Strict: a loose comparison would convert a header value that is not text. + if (in_array("text/csv", $contentType, true)) { return $this->createResponse($response, $response->getBody()->getContents()); } - return $this->createResponse($response, $this->jsonSerializer->deserialize($response->getBody())); + $text = CheckoutUtils::contentsOf($response->getBody()); + return $this->createResponse($response, $text === null ? null : $this->jsonSerializer->deserialize($text)); } /** diff --git a/lib/Checkout/CheckoutApi.php b/lib/Checkout/CheckoutApi.php index 60498339..0d394a86 100644 --- a/lib/Checkout/CheckoutApi.php +++ b/lib/Checkout/CheckoutApi.php @@ -53,8 +53,13 @@ final class CheckoutApi extends CheckoutApmApi private $forwardClient; - 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); @@ -271,8 +276,10 @@ public function getForwardClient() * @param CheckoutConfiguration $configuration * @return ApiClient */ - private function getBaseApiClient(CheckoutConfiguration $configuration) - { + private function getBaseApiClient( + #[\SensitiveParameter] + CheckoutConfiguration $configuration + ) { $baseUri = $configuration->getEnvironment()->getBaseUri(); $subdomain = $configuration->getEnvironmentSubdomain(); @@ -286,8 +293,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()); } @@ -295,8 +304,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()); } @@ -304,8 +315,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..860a7484 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|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; /** - * @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 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(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] + ?ResponseInterface $response + ) { + if ($response === null) { + return null; + } + try { + $headers = array_filter($response->getHeaders(), function ($name) { + return !in_array(self::plainHeaderName($name), ["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 (\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 c16088d9..5136d539 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 11702f48..b33bda47 100644 --- a/lib/Checkout/CheckoutUtils.php +++ b/lib/Checkout/CheckoutUtils.php @@ -3,7 +3,10 @@ namespace Checkout; use DateTime; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\Response; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\StreamInterface; class CheckoutUtils { @@ -81,4 +84,138 @@ public static function getHttpMetadata(?Response $http_response = null): ?HttpMe $http_response->getProtocolVersion() ); } + + /** + * The response of an HTTP client failure. For internal use by the SDK. + * + * @internal + * @param \Throwable $failure any failure; 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] + \Throwable $failure + ): ?ResponseInterface { + if (!$failure instanceof RequestException) { + return null; + } + try { + return $failure->getResponse(); + } 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] + ?ResponseInterface $response + ): ?int { + if ($response === null) { + return null; + } + try { + $status = $response->getStatusCode(); + } catch (\Throwable $unreadable) { + return null; + } + return is_int($status) ? $status : null; + } + + /** + * 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 + * @return string|null null when there is no response or its body cannot be read + */ + public static function bodyOf( + #[\SensitiveParameter] + ?ResponseInterface $response + ): ?string { + if ($response === null) { + return null; + } + try { + return self::contentsOf($response->getBody()); + } catch (\Throwable $unreadable) { + return null; + } + } + + /** + * The text of a stream: all of it when the stream is seekable, otherwise what remains + * unread. For internal use by the SDK. + * + * Read with rewind() and getContents(), not __toString(): an exception thrown inside + * __toString() cannot be caught before PHP 7.4, on the lines that share this code. + * + * @internal + * @param StreamInterface $stream the stream to read + * @return string|null the text; null when getContents() gives anything else, since converting + * another value could call a __toString() that throws + * @throws \Throwable when the stream cannot be read; callers wrap the failure + */ + public static function contentsOf( + #[\SensitiveParameter] + StreamInterface $stream + ): ?string { + 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 $failure + * @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] + \Throwable $failure + ): string { + $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 (\Throwable $unreadable) { + $context = null; + } + $errno = is_array($context) ? ($context["errno"] ?? null) : null; + if (is_int($errno)) { + return $class . " (cURL error " . $errno . ")"; + } + } + return $class; + } } diff --git a/lib/Checkout/Forward/ForwardClient.php b/lib/Checkout/Forward/ForwardClient.php index 1e597268..36ec2ad8 100644 --- a/lib/Checkout/Forward/ForwardClient.php +++ b/lib/Checkout/Forward/ForwardClient.php @@ -29,8 +29,10 @@ public function __construct(ApiClient $apiClient, CheckoutConfiguration $configu * @return array * @throws CheckoutApiException */ - public function forwardAnApiRequest(ForwardRequest $forwardRequest) - { + public function forwardAnApiRequest( + #[\SensitiveParameter] + ForwardRequest $forwardRequest + ) { return $this->apiClient->post( $this->buildPath(self::FORWARD_PATH), $forwardRequest, 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 a1e1b07f..ddb0a92c 100644 --- a/lib/Checkout/OAuthAccessToken.php +++ b/lib/Checkout/OAuthAccessToken.php @@ -17,8 +17,12 @@ class OAuthAccessToken * @param string $tokenType * @param DateTime $expirationDate */ - public function __construct($token, $tokenType, DateTime $expirationDate) - { + public function __construct( + #[\SensitiveParameter] + $token, + $tokenType, + DateTime $expirationDate + ) { $this->token = $token; $this->tokenType = $tokenType; $this->expirationDate = $expirationDate; diff --git a/lib/Checkout/OAuthSdkCredentials.php b/lib/Checkout/OAuthSdkCredentials.php index 7e8b1b9d..f9dbc286 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 { @@ -15,6 +14,18 @@ class OAuthSdkCredentials implements SdkCredentialsInterface */ private const MAX_EXPIRES_IN_SECONDS = 31536000; + /** + * Error codes of a token error response (RFC 6749, section 5.2). + */ + private const OAUTH_ERROR_CODES = [ + "invalid_request", + "invalid_client", + "invalid_grant", + "unauthorized_client", + "unsupported_grant_type", + "invalid_scope", + ]; + private $client; private $clientId; private $clientSecret; @@ -24,14 +35,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 @@ -45,17 +58,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 @@ -108,10 +123,11 @@ private function getAccessToken() "scope" => implode(" ", $this->scopes) ] ]); - } catch (Exception $e) { - throw new CheckoutException($e->getMessage()); + $text = CheckoutUtils::contentsOf($response->getBody()); + $body = $text === null ? null : json_decode($text, true); + } 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 +138,30 @@ private function getAccessToken() return $this->accessToken; } + /** + * @param \Throwable $failure + * @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] + \Throwable $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) ? ($body["error"] ?? null) : null; + if (is_string($error) && in_array($error, self::OAUTH_ERROR_CODES, true)) { + $message .= " (" . $error . ")"; + } + return $message; + } + /** * @param mixed $body decoded token response * @return bool true when it carries a non-empty access_token made of visible ASCII characters diff --git a/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..8f61c776 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([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 : [$header]; + if ($values === [] || 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 f907de8e..4c8d8b0a 100644 --- a/lib/Checkout/Sessions/SessionsClient.php +++ b/lib/Checkout/Sessions/SessionsClient.php @@ -48,8 +48,11 @@ public function requestSession(SessionRequest $sessionRequest): array * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function getSessionDetails(string $sessionId, ?string $sessionSecret = null): array - { + public function getSessionDetails( + string $sessionId, + #[\SensitiveParameter] + ?string $sessionSecret = null + ): array { return $this->apiClient->get( $this->buildPath(self::SESSIONS_PATH, $this->encodePathSegment($sessionId)), $this->getSdkAuthorization($sessionSecret) @@ -68,6 +71,7 @@ public function getSessionDetails(string $sessionId, ?string $sessionSecret = nu public function updateSession( string $sessionId, ChannelData $channelData, + #[\SensitiveParameter] ?string $sessionSecret = null ): array { return $this->apiClient->put( @@ -85,8 +89,11 @@ public function updateSession( * @throws CheckoutAuthorizationException * @throws CheckoutArgumentException */ - public function completeSession(string $sessionId, ?string $sessionSecret = null): array - { + public function completeSession( + string $sessionId, + #[\SensitiveParameter] + ?string $sessionSecret = null + ): array { return $this->apiClient->post( $this->buildPath(self::SESSIONS_PATH, $this->encodePathSegment($sessionId), self::COMPLETE_PATH), null, @@ -106,6 +113,7 @@ public function completeSession(string $sessionId, ?string $sessionSecret = null public function updateThreeDsMethodCompletionIndicator( string $sessionId, ThreeDsMethodCompletionRequest $threeDsMethodCompletionRequest, + #[\SensitiveParameter] ?string $sessionSecret = null ): array { return $this->apiClient->put( @@ -120,8 +128,10 @@ public function updateThreeDsMethodCompletionIndicator( * @return SdkAuthorization * @throws CheckoutAuthorizationException */ - private function getSdkAuthorization(?string $sessionSecret = null): SdkAuthorization - { + private function getSdkAuthorization( + #[\SensitiveParameter] + ?string $sessionSecret = null + ): SdkAuthorization { if ($sessionSecret === null) { return $this->sdkAuthorization(); } 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 766910e1..3a585368 100644 --- a/lib/Checkout/Webhooks/Previous/WebhooksClient.php +++ b/lib/Checkout/Webhooks/Previous/WebhooksClient.php @@ -57,6 +57,7 @@ public function retrieveWebhook(string $webhookId): array * @throws CheckoutApiException */ public function registerWebhook( + #[\SensitiveParameter] WebhookRequest $webhookRequest, ?string $idempotencyKey = null ): array { @@ -77,6 +78,7 @@ public function registerWebhook( */ public function updateWebhook( string $webhookId, + #[\SensitiveParameter] WebhookRequest $webhookRequest ): array { return $this->apiClient->put( @@ -95,6 +97,7 @@ public function updateWebhook( */ public function patchWebhook( string $webhookId, + #[\SensitiveParameter] WebhookRequest $webhookRequest ): array { return $this->apiClient->patch( 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/ErrorHandlingTest.php b/test/Checkout/Tests/ErrorHandlingTest.php new file mode 100644 index 00000000..515d5c48 --- /dev/null +++ b/test/Checkout/Tests/ErrorHandlingTest.php @@ -0,0 +1,1674 @@ +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; + return [ + "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")], + "error in the HTTP client" => [self::errorInTheHttpClient()], + "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}') + ], + ]; + } + + /** + * @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 = CheckoutSdk::builder()->previous()->staticKeys() + ->secretKey(self::PREVIOUS_SECRET_KEY) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient([$response])) + ->logger($this->logger()) + ->build(); + + $this->assertErrorsClean(function () use ($api) { + $api->getCustomersClient()->get("cus_123"); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider sessionRequestFailures + */ + public function sessionRequestFailuresLeaveErrorsClean(string $method, $response) + { + $sessions = $this->staticKeysApi([$response])->getSessionsClient(); + + $this->assertErrorsClean(function () use ($sessions, $method) { + self::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(string $case) + { + $secret = self::sessionValues()[$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 . "\u{0085}", + "right-to-left override" => $value . "\u{202E}", + "full-width" => "sek_" . $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), + ]; + } + + /** + * @test + * @dataProvider forwardRequestFailures + */ + public function forwardRequestFailuresLeaveErrorsClean(string $method, $response) + { + $forward = $this->staticKeysApi([$response])->getForwardClient(); + + $this->assertErrorsClean(function () use ($forward, $method) { + self::callForward($forward, $method); + }, CheckoutApiException::class); + } + + public static function forwardRequestFailures() + { + $cases = []; + foreach (["forwardAnApiRequest"] as $method) { + foreach (self::apiFailures() as $name => $response) { + $cases[$method . ", " . $name] = [$method, $response[0]]; + } + } + return $cases; + } + + /** + * @test + */ + public function forwardRequestThatCannotBeSerializedLeavesErrorsClean() + { + $forward = $this->staticKeysApi([new Response(200, [], "{}")])->getForwardClient(); + $headers = new Headers(); + $headers->raw = ["Authorization" => self::FORWARD_SECRET]; + $destination = new DestinationRequest(); + $destination->url = "https://example.com/payments"; + $destination->headers = $headers; + $request = new ForwardRequest(); + $request->destination_request = $destination; + $request->reference = new class implements \IteratorAggregate { + public function getIterator(): \Iterator + { + throw new \Error("cannot iterate"); + } + }; + + $this->assertErrorsClean(function () use ($forward, $request) { + $forward->forwardAnApiRequest($request); + }, CheckoutApiException::class); + } + + /** + * @test + * @dataProvider invalidDefaultKeys + */ + public function invalidKeysLeaveErrorsClean(string $case) + { + $key = self::invalidKeys(self::INVALID_DEFAULT_KEY, self::INVALID_PREVIOUS_KEY)[$case]; + $builder = CheckoutSdk::builder()->staticKeys() + ->secretKey($key) + ->environment(Environment::sandbox()) + ->logger($this->logger()); + + $this->assertErrorsClean(function () use ($builder) { + $builder->build(); + }, CheckoutArgumentException::class); + } + + /** + * @test + * @dataProvider invalidPreviousKeys + */ + public function invalidPreviousKeysLeaveErrorsClean(string $case) + { + $key = self::invalidKeys(self::INVALID_PREVIOUS_KEY, self::INVALID_DEFAULT_KEY)[$case]; + $builder = CheckoutSdk::builder()->previous()->staticKeys() + ->secretKey($key) + ->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 + */ + 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 class { + public function __toString() + { + return ErrorHandlingTest::SECRET_KEY . "\n"; + } + }; + $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 class { + private $reads = 0; + + public function __toString() + { + return ErrorHandlingTest::SECRET_KEY . ($this->reads++ < 2 ? "" : "\r\nX: y"); + } + }; + $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(string $platform, string $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) { + $apiClient->get( + "/customers/cus_123", + new SdkAuthorization( + PlatformType::$$platform, + ErrorHandlingTest::unsendableValues()[$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(string $method, $response) + { + $this->assertErrorsClean(function () use ($method, $response) { + self::callWithSensitiveFields($this, $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 valuesThatAreNotText + */ + public function valuesThatAreNotTextAreRefusedBeforeTheRequest(string $platform, string $case) + { + $sent = []; + $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->assertSame([], $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(); + + try { + $sessions->getSessionDetails("sid_123", self::SESSION_SECRET); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + $this->assertSame( + self::connectionFailureMessage("GuzzleHttp\\Exception\\ConnectException"), + $e->getMessage() + ); + } + $this->assertSame(["sessions/sid_123 error: GuzzleHttp\\Exception\\ConnectException"], $this->errorLines()); + } + + /** + * @test + */ + public function transportFailureMessageKeepsTheTransportErrorNumber() + { + $sessions = $this->staticKeysApi([ + function (RequestInterface $request) { + throw new ConnectException("Could not resolve host", $request, null, ["errno" => 6]); + } + ])->getSessionsClient(); + + try { + $sessions->getSessionDetails("sid_123", self::SESSION_SECRET); + $this->fail("expected an exception"); + } catch (CheckoutApiException $e) { + $this->assertSame( + self::connectionFailureMessage("GuzzleHttp\\Exception\\ConnectException (cURL error 6)"), + $e->getMessage() + ); + } + $this->assertSame( + ["sessions/sid_123 error: GuzzleHttp\\Exception\\ConnectException (cURL error 6)"], + $this->errorLines() + ); + } + + /** + * A failed connection is described by its class and the transport error number, whether or not + * the HTTP client's connection failure is a RequestException (Guzzle 6) or not (Guzzle 7). + * + * @test + */ + public function failedConnectionIsDescribedByItsClassAndTransportErrorNumber() + { + $failure = new ConnectException( + "Could not resolve host " . self::SECRET_KEY, + new Request("GET", "https://x", ["Authorization" => self::SECRET_KEY]), + null, + ["errno" => 6, "error" => "Could not resolve host " . self::SECRET_KEY] + ); + + $this->assertSame( + "GuzzleHttp\\Exception\\ConnectException (cURL error 6)", + CheckoutUtils::describeFailure($failure) + ); + } + + /** + * @test + */ + public function failedConnectionThroughTheHttpClientIsDescribedByItsClassAndTransportErrorNumber() + { + $customers = $this->staticKeysApi([ + function (RequestInterface $request) { + throw new ConnectException("Could not resolve host", $request, null, ["errno" => 6]); + } + ])->getCustomersClient(); + + $this->assertErrorsClean(function () use ($customers) { + $customers->get("cus_123"); + }, CheckoutApiException::class); + $this->assertSame( + ["customers/cus_123 error: GuzzleHttp\\Exception\\ConnectException (cURL error 6)"], + $this->errorLines() + ); + } + + /** + * @param string $description the description of the failure + * @return string the message of the CheckoutApiException raised for a failed connection: with + * Guzzle 6 the failure is a RequestException without a response, described by the status + * code message as before + */ + private static function connectionFailureMessage(string $description) + { + return is_subclass_of(ConnectException::class, RequestException::class) + ? "The API response status code (0) does not indicate success." + : $description; + } + + /** + * @return string[] the messages of the error records of the log + */ + private function errorLines() + { + $lines = []; + foreach ($this->logs->getRecords() as $record) { + // 400 is the ERROR level on every Monolog version. + if ($record["level"] >= 400) { + $lines[] = $record["message"]; + } + } + return $lines; + } + + /** + * @test + */ + public function responseHeadersAreKeptWithoutCookies() + { + $e = $this->failedCustomersCall(function () { + return new Response(422, [ + "Cko-Request-Id" => "req_123", + "Set-Cookie" => "session=" . self::RESPONSE_COOKIE, + "set-cookie2" => "legacy=" . self::RESPONSE_COOKIE, + ], '{"error_type":"request_invalid"}'); + }); + + $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 successfulResponseHeadersAreKeptAsTheyAre() + { + $result = $this->staticKeysApi([new Response(200, [ + "Cko-Request-Id" => "req_123", + "Set-Cookie" => "session=abc", + ], '{"id":"cus_123"}')])->getCustomersClient()->get("cus_123"); + + $this->assertSame(["session=abc"], $result["http_metadata"]->getHeaders()["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\u{200B}-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 = new class (401, [], '{"error_type":"request_unauthorized"}') extends Response { + public function getHeaders(): array + { + throw 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 class ("failed", $request, new Response(401)) extends RequestException { + public function __construct($message, RequestInterface $request, ResponseInterface $response) + { + parent::__construct($message, $request, $response); + $this->code = 500; + } + }; + }); + + $this->assertSame("The API response status code (401) does not indicate success.", $e->getMessage()); + } + + /** + * @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; + } + + /** + * A body is read with getContents(), so a stream whose string form fails is still read, and a + * failure while reading it is wrapped, on every PHP version. + * + * @test + * @dataProvider responsesWithAFailingStringForm + */ + public function bodyIsReadWithoutItsStringForm(string $case) + { + $body = function ($text) { + return FnStream::decorate(Utils::streamFor($text), [ + "__toString" => function () { + throw new \RuntimeException("failed " . ErrorHandlingTest::FAILURE_CODE); + }, + ]); + }; + $token = '{"access_token":"' . self::ACCESS_TOKEN . '","expires_in":3600}'; + switch ($case) { + case "token": + $api = $this->oauthApi([new Response(200, [], $body($token))]); + $this->assertNotNull($api); + break; + case "token error": + $responses = [new Response(401, [], $body('{"error":"invalid_client"}'))]; + $this->assertErrorsClean(function () use ($responses) { + $this->oauthApi($responses); + }, CheckoutException::class); + break; + case "API response": + $result = $this->staticKeysApi([new Response(200, [], $body('{"id":"cus_123"}'))]) + ->getCustomersClient()->get("cus_123"); + $this->assertSame("cus_123", $result["id"]); + break; + default: + $customers = $this->staticKeysApi([new Response(401, [], $body('{"error_type":"x"}'))]) + ->getCustomersClient(); + $this->assertErrorsClean(function () use ($customers) { + $customers->get("cus_123"); + }, CheckoutApiException::class); + } + } + + public static function responsesWithAFailingStringForm() + { + return [ + "token" => ["token"], + "token error" => ["token error"], + "API response" => ["API response"], + "API error" => ["API error"], + ]; + } + + /** + * Values that are not text, from a stream or a response without return types (psr/http-message + * 1.0), are not converted: the body is then treated as empty. + * + * @test + * @dataProvider valuesThatAreNotTextInAResponse + */ + public function responseValuesThatAreNotTextAreNotConverted(string $case) + { + $loud = function () { + return new class { + public function __toString() + { + throw new \RuntimeException("failed " . ErrorHandlingTest::FAILURE_CODE); + } + }; + }; + if ($case === "content type") { + $response = new class (200, [], '{"id":"cus_123"}') extends Response { + public $loud; + + public function getHeader($header): array + { + return strtolower($header) === "content-type" ? [($this->loud)()] : parent::getHeader($header); + } + }; + $response->loud = $loud; + $result = $this->staticKeysApi([$response])->getCustomersClient()->get("cus_123"); + $this->assertSame("cus_123", $result["id"]); + return; + } + if ((new \ReflectionMethod(StreamInterface::class, "getContents"))->hasReturnType()) { + $this->markTestSkipped("this psr/http-message declares return types"); + } + $body = function () use ($loud) { + return FnStream::decorate(Utils::streamFor("{}"), ["getContents" => $loud]); + }; + switch ($case) { + case "token": + $this->assertErrorsClean(function () use ($body) { + $this->oauthApi([new Response(200, [], $body())]); + }, CheckoutAuthorizationException::class); + break; + case "token error": + $this->assertErrorsClean(function () use ($body) { + $this->oauthApi([new Response(401, [], $body())]); + }, CheckoutException::class); + break; + case "API response": + $result = $this->staticKeysApi([new Response(200, [], $body())])->getCustomersClient()->get("cus_123"); + $this->assertArrayNotHasKey("id", $result); + break; + default: + $customers = $this->staticKeysApi([new Response(401, [], $body())])->getCustomersClient(); + $this->assertErrorsClean(function () use ($customers) { + $customers->get("cus_123"); + }, CheckoutApiException::class); + } + } + + public static function valuesThatAreNotTextInAResponse() + { + return [ + "token" => ["token"], + "token error" => ["token error"], + "API response" => ["API response"], + "API error" => ["API error"], + "content type" => ["content type"], + ]; + } + + /** + * A response class without return types (psr/http-message 1.0) can return values of any type; + * metadata is then left empty. + * + * @test + */ + public function errorMetadataIsLeftEmptyWhenItsValuesHaveUnexpectedTypes() + { + if ((new \ReflectionMethod(ResponseInterface::class, "getStatusCode"))->hasReturnType()) { + $this->markTestSkipped("this psr/http-message declares return types"); + } + $response = \Mockery::mock(ResponseInterface::class); + $response->shouldReceive("getStatusCode")->andReturn("401"); + $response->shouldReceive("getReasonPhrase")->andReturn(["Unauthorized"]); + $response->shouldReceive("getProtocolVersion")->andReturn(new \stdClass()); + $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); + } + + /** + * @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 \Checkout\Files\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 failureOfAnAnonymousClassIsNamedWithoutItsFile() + { + $sessions = $this->staticKeysApi([ + function () { + throw 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, string $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 with getAttributes(), available from PHP 8.0. + * + * @test + */ + public function everySensitiveParameterIsMarked() + { + if (PHP_VERSION_ID < 80000) { + $this->markTestSkipped("parameter attributes are read from PHP 8.0"); + } + $carrierTypes = [ + "Checkout\\SdkAuthorization", + "Checkout\\SdkCredentialsInterface", + "Checkout\\OAuthAccessToken", + "GuzzleHttp\\Exception\\RequestException", + "Throwable", + "Checkout\\Forward\\Requests\\ForwardRequest", + "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", + "Checkout\\Forward\\Requests\\DestinationRequest", + "Checkout\\Forward\\Requests\\Headers", + "Checkout\\Forward\\Requests\\Signatures\\DlocalParameters", + ]; + // Classes whose field of the same name is not a credential: payment data (wallet token + // signatures), risk data key/value pairs and the If-Match header. + $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. + $byPosition = [ + "Checkout\\AbstractStaticKeysCheckoutSdkBuilder::validateSecretKey" => ["key"], + "Checkout\\AbstractStaticKeysCheckoutSdkBuilder::validKey" => ["key"], + "Checkout\\SdkAuthorization::__construct" => ["credential"], + "Checkout\\SdkAuthorization::asText" => ["value"], + "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; + } + foreach ($method->getParameters() as $parameter) { + $required = $this->carriesCredentialByName($parameter) + || $this->hasType($parameter, $carrierTypes) + || ($httpClientBuilt && $this->hasType($parameter, $configurationTypes)) + || in_array($parameter->getName(), $byPosition[$id] ?? [], true) + || 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\\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; + } + + 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, trait and enum 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() + { + return [ + "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"))], + "error in the HTTP client" => [self::errorInTheHttpClient()], + ]; + } + + /** + * @return callable a handler that answers with a non-JSON page made of the request headers and + * body + */ + private static function errorPage(int $status, string $before = "", string $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); + }; + } + + /** + * @return callable a handler that answers with a response whose body fails when read, with a + * message made of the request headers and body + */ + private static function unreadableBody(int $status) + { + return function (RequestInterface $request) use ($status) { + $message = "failed " . json_encode($request->getHeaders()) . " " . (string)$request->getBody(); + $fail = function () use ($message) { + throw new \RuntimeException($message); + }; + $methods = ["getContents" => $fail, "read" => $fail]; + // Before PHP 7.4 a __toString that throws is a fatal error, so streams cannot fail there. + if (PHP_VERSION_ID >= 70400) { + $methods["__toString"] = $fail; + } + $body = FnStream::decorate(Utils::streamFor("{}"), $methods); + 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(string $kind) + { + return function (RequestInterface $request) use ($kind) { + $message = "failed " . json_encode($request->getHeaders()) . " " . (string)$request->getBody(); + switch ($kind) { + case "sdk": + throw new class ($message) extends CheckoutException { + }; + case "sdk factory": + throw CheckoutAuthorizationException::invalidAuthorization($message); + case "unreadable response": + throw new class ($message, $request) extends RequestException { + public function getResponse(): ?ResponseInterface + { + throw new \RuntimeException("no response"); + } + }; + case "unreadable body": + throw new RequestException($message, $request, self::unreadableBody(500)($request)); + case "text code": + throw new class ($message, $request) extends RequestException { + public function __construct($message, RequestInterface $request) + { + parent::__construct($message, $request); + $this->code = ErrorHandlingTest::FAILURE_CODE; + } + }; + case "object context": + throw new class ($message) extends \RuntimeException { + public function getHandlerContext() + { + return new \stdClass(); + } + }; + case "failing context": + throw new class ($message) extends \RuntimeException { + public function getHandlerContext() + { + throw new \LogicException("no context"); + } + }; + default: + throw new \RuntimeException($message); + } + }; + } + + /** + * @return callable a handler that raises an Error while the HTTP client frames are on the stack + */ + 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. + */ + private static function callSessions($sessions, string $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. + */ + private static function callWithSensitiveFields(self $test, string $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); + } + } + } + + private static function callForward($forward, string $method) + { + if ($method !== "forwardAnApiRequest") { + throw new \LogicException("unknown method " . $method); + } + $headers = new Headers(); + $headers->raw = ["Authorization" => self::FORWARD_SECRET]; + $destination = new DestinationRequest(); + $destination->url = "https://example.com/payments"; + $destination->headers = $headers; + $request = new ForwardRequest(); + $request->destination_request = $destination; + $forward->forwardAnApiRequest($request); + } + + /** + * @param array $responses + * @param mixed $secretKey + */ + private 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(); + } + + private function oauthApi(array $responses) + { + return CheckoutSdk::builder()->oAuth() + ->clientCredentials(self::CLIENT_ID, self::CLIENT_SECRET) + ->environment(Environment::sandbox()) + ->httpClientBuilder($this->httpClient($responses)) + ->logger($this->logger()) + ->build(); + } + + private 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(int $working, array $queue = []) + { + $client = new Client(["handler" => HandlerStack::create(new MockHandler($queue))]); + $calls = 0; + $builder = $this->createMock(HttpClientBuilderInterface::class); + $builder->method("getClient")->willReturnCallback(function () use ($client, $working, &$calls) { + if ($calls++ >= $working) { + // Created inside the SDK call, as a real client builder would. + throw new \RuntimeException("no client"); + } + return $client; + }); + return $builder; + } + + /** + * 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. + */ + private function assertErrorsClean(callable $call, string $expected) + { + try { + $call(); + } catch (Throwable $e) { + $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 = $frame["class"] ?? ""; + if (strpos($frameClass, "PHPUnit\\") === 0 || $frameClass === self::class) { + continue; + } + $this->collectStrings($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->assertFalse(strpos($text, $tag) !== false, "credential in " . $where); + } + } + return; + } + $this->fail("expected " . $expected); + } + + /** + * 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, int $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); + $strings[] = (string)$value->getBody(); + } + $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/OAuthIntegrationTest.php b/test/Checkout/Tests/OAuthIntegrationTest.php index e08ecb0a..4d849c99 100644 --- a/test/Checkout/Tests/OAuthIntegrationTest.php +++ b/test/Checkout/Tests/OAuthIntegrationTest.php @@ -4,8 +4,8 @@ use Checkout\CheckoutApiException; use Checkout\CheckoutSdk; +use Checkout\Common\AmountAllocations; use Checkout\Common\Currency; -use Checkout\Common\MarketplaceData; use Checkout\Environment; use Checkout\Payments\Request\PaymentRequest; use Checkout\Payments\Request\Source\RequestCardSource; @@ -44,8 +44,12 @@ public function shouldMakePaymentWithOAuth() $paymentIndividualSender->last_name = "Test"; $paymentIndividualSender->address = $this->getAddress(); - $marketplace = new MarketplaceData(); - $marketplace->sub_entity_id = "ent_ocw5i74vowfg2edpy66izhts2u"; + // 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; @@ -54,8 +58,8 @@ public function shouldMakePaymentWithOAuth() $paymentRequest->amount = 10; $paymentRequest->currency = Currency::$EUR; $paymentRequest->processing_channel_id = "pc_a6dabcfa2o3ejghb3sjuotdzzy"; - $paymentRequest->marketplace = $marketplace; $paymentRequest->sender = $paymentIndividualSender; + $paymentRequest->amount_allocations = array($allocation); $paymentResponse = $this->checkoutApi->getPaymentsClient()->requestPayment($paymentRequest); @@ -76,7 +80,7 @@ public function shouldFailInitAuthorizationInvalidCredentials() ->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 +98,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() + ); } }