Skip to content

Commit

Permalink
[TASK] 100% test coverage 🎉
Browse files Browse the repository at this point in the history
  • Loading branch information
cngJo committed Nov 7, 2023
1 parent 4432b01 commit 203b63a
Show file tree
Hide file tree
Showing 5 changed files with 180 additions and 23 deletions.
32 changes: 14 additions & 18 deletions src/Controller/Mamo/MetricsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public function __construct(
public function indexAction(Request $request): Response
{
$this->verifyRequest($request);
$secret = $this->getConfigurationSecret();

$registry = new CollectorRegistry(new InMemory());
$registry->getOrRegisterGauge('mamo', 'shopware6_platform', 'Shopware 6 Platform Version', ['latestVersion', 'currentVersion'])
Expand Down Expand Up @@ -71,15 +72,6 @@ public function indexAction(Request $request): Response
];

if (! $request->query->has('unsecure')) {
$secret = $this->systemConfigService->get(MobiMamoConnector::CONFIG_KEY_SECRET);
if (! is_string($secret)) {
// Can only happen, when we change our config template or Shopware itself screws up.
$this->logger->error('Configuration Secret is not a string.', [
'receivedType' => gettype($secret),
]);
throw new HttpException(500);
}

$headers['HMAC'] = hash_hmac('sha256', $result, $secret);
}

Expand All @@ -92,10 +84,7 @@ public function indexAction(Request $request): Response
*/
private function verifyRequest(Request $request): void
{
$secret = $this->systemConfigService->get(MobiMamoConnector::CONFIG_KEY_SECRET);
if (! is_string($secret)) {
throw new HttpException(500, 'Configuration Secret is not a string.');
}
$secret = $this->getConfigurationSecret();

// Handle legacy request with the secret in the query parameter.
if ($request->query->has('unsecure')) {
Expand All @@ -114,7 +103,7 @@ private function validateHmacRequest(Request $request, string $secret): void
throw new HttpException(401);
}

$body = file_get_contents('php://input');
$body = $request->getContent();
if (! $body) {
$this->logger->info('Request body is missing.');
throw new HttpException(400);
Expand All @@ -127,6 +116,16 @@ private function validateHmacRequest(Request $request, string $secret): void
}

private function validateSecretRequest(Request $request, string $secret): void
{
$secret = $this->getConfigurationSecret();

if (! $this->requestAuthorizationService->isAuthorized($request, $secret)) {
$this->logger->info('Request is not authorized to access the metrics endpoint.');
throw new HttpException(403);
}
}

private function getConfigurationSecret(): string
{
$secret = $this->systemConfigService->get(MobiMamoConnector::CONFIG_KEY_SECRET);
if (! is_string($secret)) {
Expand All @@ -137,9 +136,6 @@ private function validateSecretRequest(Request $request, string $secret): void
throw new HttpException(500);
}

if (! $this->requestAuthorizationService->isAuthorized($request, $secret)) {
$this->logger->info('Request is not authorized to access the metrics endpoint.');
throw new HttpException(403);
}
return $secret;
}
}
104 changes: 99 additions & 5 deletions tests/Controller/MetricsControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@
namespace MobilisticsGmbH\MamoConnector\Tests\Controller;

use MobilisticsGmbH\MamoConnector\MobiMamoConnector;
use MobilisticsGmbH\MamoConnector\Tests\Support\StorefrontControllerTestBehaviour;
use PHPUnit\Framework\TestCase;
use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Test\Controller\StorefrontControllerTestBehaviour;

class MetricsControllerTest extends TestCase
{
use IntegrationTestBehaviour;
use StorefrontControllerTestBehaviour;

private const TESTING_SECRET = "testing-secret";

public function testMetricsAction(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, 'testing-secret');
$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$metrics = $this->request('GET', 'mamo-connector/metrics?unsecure&secret=testing-secret', []);

Expand All @@ -31,17 +33,109 @@ public function testMetricsAction(): void
static::assertStringContainsString('mamo_shopware6_platform', $content);
}

public function testFailWhenNoSecretProvided(): void
public function testFailWithInvalidLegacySecret(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$metrics = $this->request('GET', 'mamo-connector/metrics?unsecure', []);
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(403, $metrics->getStatusCode());
}

public function testFailWithInvalidHmacHeader(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, 'testing-secret');
$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$metrics = $this->request('GET', 'mamo-connector/metrics', []);
$metrics = $this->request('GET', 'mamo-connector/metrics', [
"header" => [
"Hmac" => "dummy"
]
]);
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(401, $metrics->getStatusCode());
}

public function testValidRequestWithHmac(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$content = '{"validateTime":' . mktime(0) . '}';

$metrics = $this->request('GET', 'mamo-connector/metrics', [], [], [
"HTTP_Hmac" => hash_hmac('sha256', '{"validateTime":' . mktime(0) . '}', self::TESTING_SECRET),
], $content);
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(200, $metrics->getStatusCode());
static::assertStringContainsString('mamo_shopware6_platform', $content);
}

public function testHmacMissingBody(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$content = '{"validateTime":' . mktime(0) . '}';

$metrics = $this->request('GET', 'mamo-connector/metrics', [], [], [
"HTTP_Hmac" => hash_hmac('sha256', '{"validateTime":' . mktime(0) . '}', self::TESTING_SECRET),
], ""); // <- missing request body
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(400, $metrics->getStatusCode());
}

public function testHmacMismatch(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, self::TESTING_SECRET);

$content = '{"validateTime":' . mktime(0) . '}';

$metrics = $this->request('GET', 'mamo-connector/metrics', [], [], [
"HTTP_Hmac" => hash_hmac('sha256', '{"validateTime":' . mktime(0) . '}', self::TESTING_SECRET),
], "hmac-mismatch"); // <- missing request body
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(403, $metrics->getStatusCode());
}

/**
* NOTE: This can only happen, when we change our config template or Shopware itself screws up.
*/
public function testConfigurationSecretIsNotAString(): void
{
/** @var SystemConfigService $systemConfigService */
$systemConfigService = $this->getContainer()->get(SystemConfigService::class);

// Screw up the configuration
$systemConfigService->set(MobiMamoConnector::CONFIG_KEY_SECRET, false);

// Regular controller access
$metrics = $this->request('GET', 'mamo-connector/metrics?unsecure', []);
$content = $metrics->getContent();

static::assertNotFalse($content);
static::assertEquals(500, $metrics->getStatusCode());
}
}
15 changes: 15 additions & 0 deletions tests/MobiMamoConnectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace MobilisticsGmbH\MamoConnector\Tests;

use MobilisticsGmbH\MamoConnector\MobiMamoConnector;
use PHPUnit\Framework\TestCase;

class MobiMamoConnectorTest extends TestCase
{
public function testExecuteComposerCommandsIsSet(): void
{
$plugin = new MobiMamoConnector(true, "");
static::assertTrue($plugin->executeComposerCommands());
}
}
47 changes: 47 additions & 0 deletions tests/Support/StorefrontControllerTestBehaviour.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace MobilisticsGmbH\MamoConnector\Tests\Support;

use Shopware\Core\DevOps\Environment\EnvironmentHelper;
use Shopware\Core\Framework\Test\TestCaseBase\KernelLifecycleManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\KernelInterface;

trait StorefrontControllerTestBehaviour
{
/**
* @param array<string, mixed> $data
*/
public function request(string $method, string $path, array $data, array $files = [], array $server = [], string $content = null, bool $changeHistory = true): Response
{
$browser = KernelLifecycleManager::createBrowser($this->getKernel());
$browser->request($method, EnvironmentHelper::getVariable('APP_URL') . '/' . $path, $data, $files, $server, $content, $changeHistory);

return $browser->getResponse();
}

/**
* @param array<string, mixed> $data
*
* @return array<string, mixed>
*/
public function tokenize(string $route, array $data): array
{
$requestStack = new RequestStack();
$request = new Request();
/** @var Session $session */
$session = $this->getSession();
$request->setSession($session);
$requestStack->push($request);

return $data;
}

abstract protected static function getKernel(): KernelInterface;

abstract protected static function getContainer(): ContainerInterface;
}
5 changes: 5 additions & 0 deletions tests/Utility/VersionUtilityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,9 @@ public function testFourPartVersionNumberWithLastNumberZero(): void
$this->assertEquals(6004020000, VersionUtility::convertVersionToInteger('6.4.20.0'));
$this->assertEquals('6.4.20.0', VersionUtility::convertIntegerToVersionNumber('6004020000', 4));
}

public function testMissingVersionNumber(): void
{
$this->assertEquals(1000, VersionUtility::convertVersionToInteger('1.'));
}
}

0 comments on commit 203b63a

Please sign in to comment.