Skip to content

Commit

Permalink
Merge pull request #4 from julienloizelet/feat/metrics
Browse files Browse the repository at this point in the history
Feat/metrics
  • Loading branch information
julienloizelet committed Aug 21, 2023
2 parents dff67d0 + 0a3f558 commit 966113c
Show file tree
Hide file tree
Showing 30 changed files with 813 additions and 56 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Release
name: Create release
# example: gh workflow run release.yml -f tag_name=v1.1.4 -f draft=true
on:
workflow_dispatch:
Expand Down
129 changes: 129 additions & 0 deletions Block/Adminhtml/Report/Metrics.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php declare(strict_types=1);
/**
* CrowdSec_Engine Extension
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT LICENSE
* that is bundled with this package in the file LICENSE
*
* @category CrowdSec
* @package CrowdSec_Engine
* @copyright Copyright (c) 2023+ CrowdSec
* @author CrowdSec team
* @see https://crowdsec.net CrowdSec Official Website
* @license MIT LICENSE
*
*/

/**
*
* @category CrowdSec
* @package CrowdSec_Engine
* @module Engine
* @author CrowdSec team
*
*/

namespace CrowdSec\Engine\Block\Adminhtml\Report;

use CrowdSec\Engine\CapiEngine\Remediation;
use CrowdSec\Engine\Helper\Data as Helper;
use CrowdSec\Engine\Constants;
use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\UrlInterface as BackendUrlInterface;

class Metrics extends Template
{
/**
* @var Remediation
*/
private $remediation;
/**
* @var Helper
*/
private $helper;

/**
* @var BackendUrlInterface
*/
private $backendUrl;

/**
* @param Remediation $remediation
* @param Helper $helper
* @param BackendUrlInterface $backendUrl
* @param Context $context
* @param array $data
*/
public function __construct(
Remediation $remediation,
Helper $helper,
BackendUrlInterface $backendUrl,
Context $context,
array $data = []
) {
$this->remediation = $remediation;
$this->helper = $helper;
$this->backendUrl = $backendUrl;
$data = array_merge($data, [
'origin_capi' => Constants::ORIGIN_CAPI,
'origin_lists' => Constants::ORIGIN_LISTS,
'origin_crowdsec' => Constants::ORIGIN
]);
parent::__construct($context, $data);
}

/**
* Retrieves origin count cached item
*
* @return array
* @throws \Psr\Cache\InvalidArgumentException
*/
public function getOriginsCount(): array
{

return $this->remediation->getOriginsCount();
}

/**
* Retrieves "should bounce ban" setting
*
* @return bool
*/
public function isBanBouncingEnabled(): bool
{
return $this->helper->shouldBounceBan();
}

/**
* Retrieves "should ban locally" setting
*
* @return bool
*/
public function isLocalBanEnabled(): bool
{
return $this->helper->shouldBanLocally();
}

/**
* Retrieves "fallback" setting
*
* @return string
*/
public function getFallback(): string
{
return $this->helper->getFallbackRemediation();
}

/**
* Retrieves settings url
*
* @return string
*/
public function getSettingsUrl()
{
return $this->backendUrl->getUrl('adminhtml/system_config/edit/', ['section' => 'crowdsec_engine']);
}
}
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

---

## [0.3.0](https://github.com/crowdsecurity/magento-cs-extension/releases/tag/v0.3.0) - 2023-08-21
[_Compare with previous release_](https://github.com/crowdsecurity/magento-cs-extension/compare/v0.2.0...v0.3.0)


### Add

- Add metrics in report page

---

## [0.2.0](https://github.com/crowdsecurity/magento-cs-extension/releases/tag/v0.2.0) - 2023-08-01
[_Compare with previous release_](https://github.com/crowdsecurity/magento-cs-extension/compare/v0.1.0...v0.2.0)

Expand Down
38 changes: 20 additions & 18 deletions CapiEngine/Remediation.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,23 +41,23 @@ class Remediation extends CapiRemediation
/**
* @var Helper
*/
private $_helper;
private $helper;
/**
* @var MemcachedFactory
*/
private $_memcachedFactory;
private $memcachedFactory;
/**
* @var PhpFilesFactory
*/
private $_phpFilesFactory;
private $phpFilesFactory;
/**
* @var RedisFactory
*/
private $_redisFactory;
private $redisFactory;
/**
* @var Watcher
*/
private $_watcher;
private $watcher;

/**
* Constructor.
Expand All @@ -75,24 +75,26 @@ public function __construct(
RedisFactory $redisFactory,
MemcachedFactory $memcachedFactory
) {
$this->_helper = $helper;
$this->_watcher = $watcher;
$this->_redisFactory = $redisFactory;
$this->_memcachedFactory = $memcachedFactory;
$this->_phpFilesFactory = $phpFilesFactory;
$this->helper = $helper;
$this->watcher = $watcher;
$this->redisFactory = $redisFactory;
$this->memcachedFactory = $memcachedFactory;
$this->phpFilesFactory = $phpFilesFactory;

$logger = $this->_watcher->getLogger();
$logger = $this->watcher->getLogger();

$configs = ['fallback_remediation' => $this->helper->getFallbackRemediation()];

$cacheConfigs = [
'cache_system' => $this->_helper->getCacheTechnology(),
'cache_system' => $this->helper->getCacheTechnology(),
'fs_cache_path' => Constants::CROWDSEC_ENGINE_CACHE_PATH,
'memcached_dsn' => $this->_helper->getMemcachedDsn(),
'redis_dsn' => $this->_helper->getRedisDsn()
'memcached_dsn' => $this->helper->getMemcachedDsn(),
'redis_dsn' => $this->helper->getRedisDsn()
];

$cache = $this->handleCache($cacheConfigs, $logger);

parent::__construct([], $this->_watcher, $cache, $logger);
parent::__construct($configs, $this->watcher, $cache, $logger);
}

/**
Expand All @@ -107,13 +109,13 @@ private function handleCache(array $configs, LoggerInterface $logger): AbstractC
$cacheSystem = $configs['cache_system'] ?? Constants::CACHE_SYSTEM_PHPFS;
switch ($cacheSystem) {
case Constants::CACHE_SYSTEM_MEMCACHED:
$cache = $this->_memcachedFactory->create(['configs' => $configs, 'logger' => $logger]);
$cache = $this->memcachedFactory->create(['configs' => $configs, 'logger' => $logger]);
break;
case Constants::CACHE_SYSTEM_REDIS:
$cache = $this->_redisFactory->create(['configs' => $configs, 'logger' => $logger]);
$cache = $this->redisFactory->create(['configs' => $configs, 'logger' => $logger]);
break;
default:
$cache = $this->_phpFilesFactory->create(['configs' => $configs, 'logger' => $logger]);
$cache = $this->phpFilesFactory->create(['configs' => $configs, 'logger' => $logger]);
break;
}

Expand Down
2 changes: 1 addition & 1 deletion Constants.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,5 @@ class Constants extends CapiConstants
/** @var string The user agent suffix used to send request to CAPI */
public const USER_AGENT_SUFFIX = 'magento2';
/** @var string The last version of this module */
public const VERSION = 'v0.2.0';
public const VERSION = 'v0.3.0';
}
2 changes: 1 addition & 1 deletion Controller/Adminhtml/Events/Grid.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function execute()
{
$resultPage = $this->resultPageFactory->create();
$resultPage->setActiveMenu(self::MENU_ID);
$resultPage->getConfig()->getTitle()->prepend((__('CrowdSec Engine Events')));
$resultPage->getConfig()->getTitle()->prepend((__('CrowdSec Engine')));

return $resultPage;
}
Expand Down
37 changes: 37 additions & 0 deletions Helper/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
namespace CrowdSec\Engine\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;

class Config extends AbstractHelper
{
Expand All @@ -50,8 +51,10 @@ class Config extends AbstractHelper
public const XML_PATH_DECISIONS_CACHE_MEMCACHED_DSN = self::SECTION . '/decisions/cache/memcached_dsn';
public const XML_PATH_DECISIONS_CACHE_REDIS_DSN = self::SECTION . '/decisions/cache/redis_dsn';
public const XML_PATH_DECISIONS_CACHE_TECHNOLOGY = self::SECTION . '/decisions/cache/technology';
public const XML_PATH_DECISIONS_FALLBACK_REMEDIATION = self::SECTION . '/decisions/fallback_remediation';
public const XML_PATH_ENV = self::SECTION . '/general/environment';
public const XML_PATH_EVENT_LIFETIME = self::SECTION . '/crons/events/lifetime';
public const XML_PATH_FORCED_TEST_IP = self::SECTION . '/advanced/forced_test_ip';
public const XML_PATH_LOG_LEVEL = self::SECTION . '/advanced/log_level';
public const XML_PATH_SIGNALS_BAN_DURATION = self::SECTION . '/signals/ban_duration';
public const XML_PATH_SIGNAL_SCENARIOS = self::SECTION . '/signals/scenarios';
Expand All @@ -68,6 +71,8 @@ class Config extends AbstractHelper
'clean_events_expr' => null,
'env' => null,
'event_lifetime' => null,
'fallback_remediation' => null,
'forced_test_ip' => null,
'log_level' => null,
'memcached_dsn' => null,
'prune_cache_expr' => null,
Expand Down Expand Up @@ -167,6 +172,38 @@ public function getEventLifetime(): int
return (int)$this->_globals['event_lifetime'];
}

/**
* Get fallback remediation config
*
* @return string
*/
public function getFallbackRemediation(): string
{
if (!isset($this->_globals['fallback_remediation'])) {
$this->_globals['fallback_remediation'] = (string)$this->scopeConfig->getValue(
self::XML_PATH_DECISIONS_FALLBACK_REMEDIATION
);
}

return (string)$this->_globals['fallback_remediation'];
}

/**
* Get forced test ip config
*
* @return string
*/
public function getForcedTestIp(): string
{
if (!isset($this->_globals['forced_test_ip'])) {
$this->_globals['forced_test_ip'] = (string)$this->scopeConfig->getValue(
self::XML_PATH_FORCED_TEST_IP
);
}

return (string)$this->_globals['forced_test_ip'];
}

/**
* Get log level config.
*
Expand Down
3 changes: 2 additions & 1 deletion Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,9 @@ public function getLogger(): Logger
*/
public function getRealIp(): string
{
$forcedTestIp = $this->getForcedTestIp();
// Alternative headers have been set in DI
return $this->remoteAddress->getRemoteAddress();
return !empty($forcedTestIp) ? $forcedTestIp : $this->remoteAddress->getRemoteAddress();
}

/**
Expand Down
51 changes: 51 additions & 0 deletions Model/Config/Source/Fallback.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php declare(strict_types=1);
/**
* CrowdSec_Engine Extension
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT LICENSE
* that is bundled with this package in the file LICENSE
*
* @category CrowdSec
* @package CrowdSec_Engine
* @copyright Copyright (c) 2023+ CrowdSec
* @author CrowdSec team
* @see https://crowdsec.net CrowdSec Official Website
* @license MIT LICENSE
*
*/

/**
*
* @category CrowdSec
* @package CrowdSec_Engine
* @module Engine
* @author CrowdSec team
*
*/

namespace CrowdSec\Engine\Model\Config\Source;

use CrowdSec\Engine\Constants;
use CrowdSec\RemediationEngine\CapiRemediation;
use Magento\Framework\Data\OptionSourceInterface;

class Fallback implements OptionSourceInterface
{
/**
* Options getter
*
* @return array
*/
public function toOptionArray(): array
{
$result = [];
$orderedRemediations = array_merge(CapiRemediation::ORDERED_REMEDIATIONS, [Constants::REMEDIATION_BYPASS]);
foreach ($orderedRemediations as $remediation) {
$result[] = ['value' => $remediation, 'label' => __("$remediation")];
}

return $result;
}
}
4 changes: 3 additions & 1 deletion Observer/BanLocally.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public function execute(Observer $observer): BanLocally
* @var $event EventInterface
*/
$event = $observer->getEvent()->getAlertEvent();
$cache = $this->remediation->getCacheStorage();

$ip = $event->getIp();
$origin = Constants::ORIGIN;
Expand All @@ -104,7 +105,8 @@ public function execute(Observer $observer): BanLocally
'origin' => $origin,
'expiresAt' => time() + $this->helper->getBanDuration()]);

$this->remediation->getCacheStorage()->storeDecision($decision);
$cache->storeDecision($decision);
$cache->commit();
} catch (\Exception $e) {
$this->helper->getLogger()->error(
'Technical error while banning ip locally',
Expand Down

0 comments on commit 966113c

Please sign in to comment.