Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions .github/scripts/phpunit-in-docker.sh
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,30 @@
$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

Check failure on line 54 in .github/scripts/phpunit-in-docker.sh

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use '[[' instead of '[' for conditional tests. The '[[' construct is safer and more feature-rich.

See more on https://sonarcloud.io/project/issues?id=checkout_checkout-sdk-php&issues=AaI7ahYK5aEQ1neV-Bqd&open=AaI7ahYK5aEQ1neV-Bqd&pullRequest=430
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"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
35 changes: 27 additions & 8 deletions lib/Checkout/AbstractStaticKeysCheckoutSdkBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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
);
}
7 changes: 5 additions & 2 deletions lib/Checkout/AbstractStaticKeysSdkCredentials.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
109 changes: 76 additions & 33 deletions lib/Checkout/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
Expand All @@ -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);
}

Expand All @@ -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);
}

/**
Expand All @@ -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);
}

/**
Expand All @@ -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);
}

/**
Expand All @@ -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);
}

Expand All @@ -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);
Expand All @@ -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");
Expand All @@ -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");
Expand All @@ -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.
Expand All @@ -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);
}
}

Expand All @@ -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
Expand All @@ -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;
}

Expand All @@ -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));
}

/**
Expand Down
Loading
Loading