Skip to content
Merged
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
9 changes: 6 additions & 3 deletions src/AppLifecycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Shopware\App\SDK\Event\ShopDeletedEvent;
use Shopware\App\SDK\Exception\MalformedWebhookBodyException;
use Shopware\App\SDK\Exception\ShopNotFoundException;
use Shopware\App\SDK\Framework\RequestBodyParser;
use Shopware\App\SDK\Registration\RegistrationService;
use Shopware\App\SDK\Shop\ShopInterface;
use Shopware\App\SDK\Shop\ShopRepositoryInterface;
Expand Down Expand Up @@ -109,13 +110,15 @@
private function shouldKeepUserData(RequestInterface $request): bool
{
try {
$body = \json_decode($request->getBody()->getContents(), true, flags: \JSON_THROW_ON_ERROR);
$body = RequestBodyParser::parse($request);
} catch (\JsonException) {
throw new MalformedWebhookBodyException();
}
$request->getBody()->rewind();

return \is_array($body) && ($body['data']['payload']['keepUserData'] ?? false) === true;
return \is_array($body)

Check warning on line 118 in src/AppLifecycle.php

View workflow job for this annotation

GitHub Actions / unit

Escaped Mutant for Mutator "LogicalAnd": @@ @@ } catch (\JsonException) { throw new MalformedWebhookBodyException(); } - return \is_array($body) && \is_array($body['data'] ?? null) && \is_array($body['data']['payload'] ?? null) && ($body['data']['payload']['keepUserData'] ?? false) === true; + return (\is_array($body) && \is_array($body['data'] ?? null) || \is_array($body['data']['payload'] ?? null)) && ($body['data']['payload']['keepUserData'] ?? false) === true; } private function findShop(RequestInterface $request): ?ShopInterface {

Check warning on line 118 in src/AppLifecycle.php

View workflow job for this annotation

GitHub Actions / unit

Escaped Mutant for Mutator "LogicalAnd": @@ @@ } catch (\JsonException) { throw new MalformedWebhookBodyException(); } - return \is_array($body) && \is_array($body['data'] ?? null) && \is_array($body['data']['payload'] ?? null) && ($body['data']['payload']['keepUserData'] ?? false) === true; + return (\is_array($body) || \is_array($body['data'] ?? null)) && \is_array($body['data']['payload'] ?? null) && ($body['data']['payload']['keepUserData'] ?? false) === true; } private function findShop(RequestInterface $request): ?ShopInterface {
&& \is_array($body['data'] ?? null)
&& \is_array($body['data']['payload'] ?? null)
&& ($body['data']['payload']['keepUserData'] ?? false) === true;

Check warning on line 121 in src/AppLifecycle.php

View workflow job for this annotation

GitHub Actions / unit

Escaped Mutant for Mutator "FalseValue": @@ @@ } catch (\JsonException) { throw new MalformedWebhookBodyException(); } - return \is_array($body) && \is_array($body['data'] ?? null) && \is_array($body['data']['payload'] ?? null) && ($body['data']['payload']['keepUserData'] ?? false) === true; + return \is_array($body) && \is_array($body['data'] ?? null) && \is_array($body['data']['payload'] ?? null) && ($body['data']['payload']['keepUserData'] ?? true) === true; } private function findShop(RequestInterface $request): ?ShopInterface {
}

private function findShop(RequestInterface $request): ?ShopInterface
Expand Down
45 changes: 13 additions & 32 deletions src/Context/ContextResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use DateTimeImmutable;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Shopware\App\SDK\Context\ActionButton\ActionButtonAction;
use Shopware\App\SDK\Context\Cart\Cart;
use Shopware\App\SDK\Context\Gateway\Checkout\CheckoutGatewayAction;
Expand All @@ -31,6 +30,7 @@
use Shopware\App\SDK\Context\Webhook\WebhookAction;
use Shopware\App\SDK\Exception\MalformedWebhookBodyException;
use Shopware\App\SDK\Framework\Collection;
use Shopware\App\SDK\Framework\RequestBodyParser;
use Shopware\App\SDK\Shop\ShopInterface;

/**
Expand All @@ -48,7 +48,7 @@
*/
public function assembleWebhook(RequestInterface $request, ShopInterface $shop): WebhookAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -65,7 +65,7 @@

public function assembleActionButton(RequestInterface $request, ShopInterface $shop): ActionButtonAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand Down Expand Up @@ -109,7 +109,7 @@

public function assembleTaxProvider(RequestInterface $request, ShopInterface $shop): TaxProviderAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -125,7 +125,7 @@

public function assemblePaymentPay(RequestInterface $request, ShopInterface $shop): PaymentPayAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -144,7 +144,7 @@

public function assemblePaymentFinalize(RequestInterface $request, ShopInterface $shop): PaymentFinalizeAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -162,7 +162,7 @@

public function assemblePaymentCapture(RequestInterface $request, ShopInterface $shop): PaymentCaptureAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -180,7 +180,7 @@

public function assemblePaymentRecurringCapture(RequestInterface $request, ShopInterface $shop): PaymentRecurringAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -197,7 +197,7 @@

public function assemblePaymentValidate(RequestInterface $request, ShopInterface $shop): PaymentValidateAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -214,7 +214,7 @@

public function assemblePaymentRefund(RequestInterface $request, ShopInterface $shop): RefundAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand Down Expand Up @@ -267,7 +267,7 @@

public function assembleCheckoutGatewayRequest(RequestInterface $request, ShopInterface $shop): CheckoutGatewayAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -285,7 +285,7 @@

public function assembleContextGatewayRequest(RequestInterface $request, ShopInterface $shop): ContextGatewayAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source']) || !isset($body['data']) || !\is_array($body['data'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -302,7 +302,7 @@

public function assembleInAppPurchasesFilterRequest(RequestInterface $request, ShopInterface $shop): FilterAction
{
$body = $this->getBody($request);
$body = RequestBodyParser::parse($request);

if (!\is_array($body) || !isset($body['source']) || !\is_array($body['source'])) {
throw new MalformedWebhookBodyException();
Expand All @@ -319,25 +319,6 @@
);
}

/**
* @throws \JsonException
*/
private function getBody(RequestInterface $request): mixed
{
if ($request instanceof ServerRequestInterface) {
$body = $request->getParsedBody();

if ($body !== null) {
return $body;
}
}

$body = \json_decode($request->getBody()->getContents(), true, flags: \JSON_THROW_ON_ERROR);
$request->getBody()->rewind();

return $body;
}

/**
* @param array<string, mixed> $source
*/
Expand Down Expand Up @@ -375,7 +356,7 @@
{
foreach ($source as $key => $value) {
if (!\is_scalar($value)) {
continue;

Check warning on line 359 in src/Context/ContextResolver.php

View workflow job for this annotation

GitHub Actions / unit

Escaped Mutant for Mutator "Continue_": @@ @@ { foreach ($source as $key => $value) { if (!\is_scalar($value)) { - continue; + break; } yield (string) $value => $key; } } }
}

yield ((string) $value) => $key;
Expand Down
40 changes: 40 additions & 0 deletions src/Framework/RequestBodyParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Shopware\App\SDK\Framework;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
* Decodes the JSON body of an incoming request.
*
* When the surrounding framework already parsed the body of a PSR-7 server request into
* an array, that result is reused.
*
* @internal
*/
final class RequestBodyParser
{
/**
* @return array<array-key, mixed>|null
*
* @throws \JsonException when the body is not valid JSON
*/
public static function parse(RequestInterface $request): ?array
{
if ($request instanceof ServerRequestInterface) {
$body = $request->getParsedBody();

if (\is_array($body)) {
return $body;
}
}

$body = \json_decode($request->getBody()->getContents(), true, flags: \JSON_THROW_ON_ERROR);
$request->getBody()->rewind();

return \is_array($body) ? $body : null;
}
}
6 changes: 2 additions & 4 deletions src/Registration/RegistrationService.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Shopware\App\SDK\Exception\ShopNotFoundException;
use Shopware\App\SDK\Exception\SignatureInvalidException;
use Shopware\App\SDK\Exception\SignatureNotFoundException;
use Shopware\App\SDK\Framework\RequestBodyParser;
use Shopware\App\SDK\Shop\ShopInterface;
use Shopware\App\SDK\Shop\ShopRepositoryInterface;

Expand Down Expand Up @@ -141,8 +142,7 @@ public function register(RequestInterface $request): ResponseInterface
*/
public function registerConfirm(RequestInterface $request): ResponseInterface
{
/** @var array<string, mixed> $requestContent */
$requestContent = \json_decode($request->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR);
$requestContent = RequestBodyParser::parse($request);

if (
empty($requestContent['shopId']) ||
Expand All @@ -166,8 +166,6 @@ public function registerConfirm(RequestInterface $request): ResponseInterface
$this->registrationLogContext($request, $requestContent['shopId'], $shop->getShopUrl(), $shop)
);

$request->getBody()->rewind();

// Use dual signature verifier for registration confirmation
try {
$this->dualSignatureVerifier->authenticateRegistrationConfirmation($request, $shop, $this->appConfiguration);
Expand Down
4 changes: 2 additions & 2 deletions src/Shop/ShopResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Shopware\App\SDK\Exception\MissingShopParameterException;
use Shopware\App\SDK\Exception\ShopNotFoundException;
use Shopware\App\SDK\Exception\SignatureInvalidException;
use Shopware\App\SDK\Framework\RequestBodyParser;

/**
* Resolve and verify a request to a shop
Expand Down Expand Up @@ -45,8 +46,7 @@ public function resolveShop(RequestInterface $request): ShopInterface
*/
private function resolveFromSource(RequestInterface $request): ShopInterface
{
$body = \json_decode($request->getBody()->getContents(), true, flags: JSON_THROW_ON_ERROR);
$request->getBody()->rewind();
$body = RequestBodyParser::parse($request);

if (!is_array($body) || !isset($body['source']) || !isset($body['source']['shopId']) || !is_string($body['source']['shopId'])) {
throw new MissingShopParameterException();
Expand Down
15 changes: 15 additions & 0 deletions tests/AppLifecycleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Nyholm\Psr7\Request;
use Nyholm\Psr7\Response;
use Nyholm\Psr7\ServerRequest;
use PHPUnit\Framework\Attributes\CoversClass;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -125,6 +126,20 @@ public function testUninstallKeepsShopWhenKeepUserDataIsTrue(): void
static::assertTrue($this->events[1]->keepUserData());
}

public function testUninstallUsesTheParsedBody(): void
{
$this->shopRepository->createShop(new MockShop('123', 'https://foo.com', '1234567890'));

// an empty body stream cannot be decoded, so keeping the shop proves the parsed body was used
$request = (new ServerRequest('POST', '/?shop-id=123', [], ''))
->withParsedBody(['data' => ['payload' => ['keepUserData' => true]]]);

$response = $this->appLifecycle->delete($request);

static::assertSame(204, $response->getStatusCode());
static::assertNotNull($this->shopRepository->getShopFromId('123'));
}

public function testUninstallDeletesShopWhenKeepUserDataIsFalse(): void
{
$this->shopRepository->createShop(new MockShop('123', 'https://foo.com', '1234567890'));
Expand Down
71 changes: 71 additions & 0 deletions tests/Framework/RequestBodyParserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

declare(strict_types=1);

namespace Shopware\App\SDK\Tests\Framework;

use Nyholm\Psr7\Request;
use Nyholm\Psr7\ServerRequest;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ServerRequestInterface;
use Shopware\App\SDK\Framework\RequestBodyParser;

#[CoversClass(RequestBodyParser::class)]
class RequestBodyParserTest extends TestCase
{
public function testDecodesTheBodyOfARequest(): void
{
$request = new Request('POST', 'https://example.com', [], '{"foo": "bar"}');

static::assertSame(['foo' => 'bar'], RequestBodyParser::parse($request));
}

public function testLeavesTheBodyReadableForTheNextReader(): void
{
$request = new Request('POST', 'https://example.com', [], '{"foo": "bar"}');

RequestBodyParser::parse($request);

static::assertSame('{"foo": "bar"}', $request->getBody()->getContents());
}

public function testThrowsOnAnInvalidBody(): void
{
$request = new Request('POST', 'https://example.com', [], 'not-json');

static::expectException(\JsonException::class);
RequestBodyParser::parse($request);
}

public function testReturnsNullForABodyThatIsNotAJsonObject(): void
{
$request = new Request('POST', 'https://example.com', [], '"foo"');

static::assertNull(RequestBodyParser::parse($request));
}

public function testReusesTheParsedBodyOfAServerRequest(): void
{
$request = static::createMock(ServerRequestInterface::class);
$request->expects(static::once())->method('getParsedBody')->willReturn(['foo' => 'bar']);
$request->expects(static::never())->method('getBody');

static::assertSame(['foo' => 'bar'], RequestBodyParser::parse($request));
}

public function testFallsBackToTheBodyWhenAServerRequestWasNotParsed(): void
{
$request = new ServerRequest('POST', 'https://example.com', [], '{"foo": "bar"}');

static::assertSame(['foo' => 'bar'], RequestBodyParser::parse($request));
}

public function testFallsBackToTheBodyWhenTheParsedBodyIsNotAnArray(): void
{
$request = (new ServerRequest('POST', 'https://example.com', [], '{"foo": "bar"}'))
->withParsedBody(new \stdClass());

static::assertSame(['foo' => 'bar'], RequestBodyParser::parse($request));
}
}
Loading
Loading