Skip to content

Commit 0d908df

Browse files
feat(exception): Improve exception message
1 parent 773ab23 commit 0d908df

File tree

4 files changed

+211
-13
lines changed

4 files changed

+211
-13
lines changed

src/AbstractBouncer.php

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public function clearCache(): bool
101101
try {
102102
return $this->getRemediationEngine()->clearCache();
103103
} catch (\Exception $e) {
104-
throw new BouncerException($e->getMessage(), (int)$e->getCode(), $e);
104+
throw new BouncerException('Error while clearing cache: ' . $e->getMessage(), (int)$e->getCode(), $e);
105105
}
106106
}
107107

@@ -193,7 +193,7 @@ public function pruneCache(): bool
193193
try {
194194
return $this->getRemediationEngine()->pruneCache();
195195
} catch (\Exception $e) {
196-
throw new BouncerException($e->getMessage(), (int)$e->getCode(), $e);
196+
throw new BouncerException('Error while pruning cache: ' . $e->getMessage(), (int)$e->getCode(), $e);
197197
}
198198
}
199199

@@ -210,7 +210,7 @@ public function refreshBlocklistCache(): array
210210
try {
211211
return $this->getRemediationEngine()->refreshDecisions();
212212
} catch (\Exception $e) {
213-
throw new BouncerException($e->getMessage(), (int)$e->getCode(), $e);
213+
throw new BouncerException('Error while refreshing decisions: ' . $e->getMessage(), (int)$e->getCode(), $e);
214214
}
215215
}
216216

@@ -288,7 +288,11 @@ public function testCacheConnection(): void
288288
$cache = $this->getRemediationEngine()->getCacheStorage();
289289
$cache->getItem(AbstractCache::CONFIG);
290290
} catch (\Exception $e) {
291-
throw new BouncerException($e->getMessage(), (int)$e->getCode(), $e);
291+
throw new BouncerException(
292+
'Error while testing cache connection: ' . $e->getMessage(),
293+
(int)$e->getCode(),
294+
$e
295+
);
292296
}
293297
}
294298

tests/Integration/IpVerificationTest.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
* @covers \CrowdSecBouncer\StandaloneBouncer::getRemediationForIp
1919
* @covers \CrowdSecBouncer\AbstractBouncer::clearCache
2020
* @covers \CrowdSecBouncer\AbstractBouncer::pruneCache
21+
* @covers \CrowdSecBouncer\AbstractBouncer::testCacheConnection
2122
*
2223
* @uses \CrowdSecBouncer\AbstractBouncer::__construct
2324
* @uses \CrowdSecBouncer\AbstractBouncer::capRemediationLevel
@@ -413,8 +414,6 @@ public function testCanVerifyIpInStreamModeWithCacheSystem($cacheAdapterName, $o
413414

414415
$bouncer->refreshBlocklistCache();
415416

416-
$bouncer->refreshBlocklistCache();
417-
418417
$this->assertEquals(
419418
'ban',
420419
$bouncer->getRemediationForIp(TestHelpers::BAD_IP),
@@ -447,8 +446,6 @@ public function testCanVerifyIpInStreamModeWithCacheSystem($cacheAdapterName, $o
447446
// Pull updates
448447
$bouncer->refreshBlocklistCache();
449448

450-
$this->logger->debug('', ['message' => 'Refresh 2nd time the cache. Nothing should append.']);
451-
$bouncer->refreshBlocklistCache();
452449

453450
$this->assertEquals(
454451
'ban',
@@ -520,6 +517,10 @@ public function testCanVerifyIpInStreamModeWithCacheSystem($cacheAdapterName, $o
520517
$cappedRemediation,
521518
'The remediation for the banned IPV6 with a too large range should now be "bypass" as we are in stream mode'
522519
);
520+
521+
// Test cache connection
522+
$bouncer->testCacheConnection();
523+
523524
}
524525

525526
/**

tests/Unit/AbstractBouncerTest.php

Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace CrowdSecBouncer\Tests\Unit;
6+
7+
/**
8+
* Test for templating.
9+
*
10+
* @author CrowdSec team
11+
*
12+
* @see https://crowdsec.net CrowdSec Official Website
13+
*
14+
* @copyright Copyright (c) 2022+ CrowdSec
15+
* @license MIT License
16+
*/
17+
18+
use CrowdSecBouncer\BouncerException;
19+
use PHPUnit\Framework\TestCase;
20+
use CrowdSecBouncer\AbstractBouncer;
21+
use CrowdSecBouncer\Constants;
22+
use CrowdSec\RemediationEngine\LapiRemediation;
23+
24+
/**
25+
* @covers \CrowdSecBouncer\AbstractBouncer::__construct
26+
* @covers \CrowdSecBouncer\AbstractBouncer::pruneCache
27+
* @covers \CrowdSecBouncer\AbstractBouncer::clearCache
28+
* @covers \CrowdSecBouncer\AbstractBouncer::refreshBlocklistCache
29+
* @covers \CrowdSecBouncer\AbstractBouncer::testCacheConnection
30+
*
31+
* @uses \CrowdSecBouncer\AbstractBouncer::configure
32+
* @uses \CrowdSecBouncer\AbstractBouncer::getConfigs
33+
* @uses \CrowdSecBouncer\AbstractBouncer::getLogger
34+
* @covers \CrowdSecBouncer\AbstractBouncer::getRemediationEngine
35+
* @uses \CrowdSecBouncer\Configuration::addBouncerNodes
36+
* @uses \CrowdSecBouncer\Configuration::addCacheNodes
37+
* @uses \CrowdSecBouncer\Configuration::addConnectionNodes
38+
* @uses \CrowdSecBouncer\Configuration::addDebugNodes
39+
* @uses \CrowdSecBouncer\Configuration::addTemplateNodes
40+
* @uses \CrowdSecBouncer\Configuration::getConfigTreeBuilder
41+
*
42+
*/
43+
final class AbstractBouncerTest extends TestCase
44+
{
45+
46+
protected $configs = [
47+
#============================================================================#
48+
# Bouncer configs
49+
#============================================================================#
50+
'use_curl' => false,
51+
'debug_mode' => true,
52+
'disable_prod_log' => false,
53+
'log_directory_path' => __DIR__ . '/.logs',
54+
'display_errors' => true,
55+
'forced_test_ip' => '',
56+
'forced_test_forwarded_ip' => '',
57+
'bouncing_level' => Constants::BOUNCING_LEVEL_NORMAL,
58+
'trust_ip_forward_array' => [],
59+
'excluded_uris' => [],
60+
'cache_system' => Constants::CACHE_SYSTEM_PHPFS,
61+
'captcha_cache_duration' => Constants::CACHE_EXPIRATION_FOR_CAPTCHA,
62+
'custom_css' => '',
63+
'hide_mentions' => false,
64+
'color' => [
65+
'text' => [
66+
'primary' => 'black',
67+
'secondary' => '#AAA',
68+
'button' => 'white',
69+
'error_message' => '#b90000',
70+
],
71+
'background' => [
72+
'page' => '#eee',
73+
'container' => 'white',
74+
'button' => '#626365',
75+
'button_hover' => '#333',
76+
],
77+
],
78+
'text' => [
79+
'captcha_wall' => [
80+
'tab_title' => 'Oops..',
81+
'title' => 'Hmm, sorry but...',
82+
'subtitle' => 'Please complete the security check.',
83+
'refresh_image_link' => 'refresh image',
84+
'captcha_placeholder' => 'Type here...',
85+
'send_button' => 'CONTINUE',
86+
'error_message' => 'Please try again.',
87+
'footer' => '',
88+
],
89+
'ban_wall' => [
90+
'tab_title' => 'Oops..',
91+
'title' => '🤭 Oh!',
92+
'subtitle' => 'This page is protected against cyber attacks and your IP has been banned by our system.',
93+
'footer' => '',
94+
],
95+
],
96+
#============================================================================#
97+
# Client configs
98+
#============================================================================#
99+
'auth_type' => Constants::AUTH_KEY,
100+
'tls_cert_path' => '',
101+
'tls_key_path' => '',
102+
'tls_verify_peer' => true,
103+
'tls_ca_cert_path' => '',
104+
'api_key' => 'unit-test',
105+
'api_url' => Constants::DEFAULT_LAPI_URL,
106+
'api_timeout' => 1,
107+
#============================================================================#
108+
# Remediation engine configs
109+
#============================================================================#
110+
'fallback_remediation' => Constants::REMEDIATION_CAPTCHA,
111+
'ordered_remediations' => [Constants::REMEDIATION_BAN, Constants::REMEDIATION_CAPTCHA],
112+
'fs_cache_path' => __DIR__ . '/.cache',
113+
'redis_dsn' => 'redis://localhost:6379',
114+
'memcached_dsn' => 'memcached://localhost:11211',
115+
'clean_ip_cache_duration' => 1,
116+
'bad_ip_cache_duration' => 1,
117+
'stream_mode' => false,
118+
'geolocation' => [
119+
'enabled' => false,
120+
'type' => Constants::GEOLOCATION_TYPE_MAXMIND,
121+
'cache_duration' => Constants::CACHE_EXPIRATION_FOR_GEO,
122+
'maxmind' => [
123+
'database_type' => Constants::MAXMIND_COUNTRY,
124+
'database_path' => '/some/path/GeoLite2-Country.mmdb',
125+
],
126+
],
127+
];
128+
129+
public function testCacheMethodsException()
130+
{
131+
$configs = $this->configs;
132+
$mockRemediation = $this->getMockBuilder(LapiRemediation::class)
133+
->disableOriginalConstructor()
134+
->onlyMethods(['pruneCache', 'clearCache', 'refreshDecisions', 'getCacheStorage'])
135+
->getMock();
136+
$client = $this->getMockForAbstractClass(AbstractBouncer::class, [$configs, $mockRemediation]);
137+
138+
$this->assertInstanceOf(LapiRemediation::class, $client->getRemediationEngine());
139+
140+
$mockRemediation->method('pruneCache')->willThrowException(new \Exception('unit test prune cache', 123));
141+
142+
$errorMessage = '';
143+
$errorCode = 0;
144+
try {
145+
$client->pruneCache();
146+
} catch (BouncerException $e) {
147+
$errorMessage = $e->getMessage();
148+
$errorCode = $e->getCode();
149+
}
150+
151+
$this->assertEquals(123, $errorCode);
152+
$this->assertEquals('Error while pruning cache: unit test prune cache', $errorMessage);
153+
154+
$mockRemediation->method('clearCache')->willThrowException(new \Exception('unit test clear cache', 456));
155+
156+
$errorMessage = '';
157+
$errorCode = 0;
158+
try {
159+
$client->clearCache();
160+
} catch (BouncerException $e) {
161+
$errorMessage = $e->getMessage();
162+
$errorCode = $e->getCode();
163+
}
164+
165+
$this->assertEquals(456, $errorCode);
166+
$this->assertEquals('Error while clearing cache: unit test clear cache', $errorMessage);
167+
168+
$mockRemediation->method('refreshDecisions')->willThrowException(new \Exception('unit test refresh', 789));
169+
170+
$errorMessage = '';
171+
$errorCode = 0;
172+
try {
173+
$client->refreshBlocklistCache();
174+
} catch (BouncerException $e) {
175+
$errorMessage = $e->getMessage();
176+
$errorCode = $e->getCode();
177+
}
178+
179+
$this->assertEquals(789, $errorCode);
180+
$this->assertEquals('Error while refreshing decisions: unit test refresh', $errorMessage);
181+
182+
$mockRemediation->method('getCacheStorage')->willThrowException(new \Exception('unit test get cache storage',
183+
101112));
184+
185+
$errorMessage = '';
186+
$errorCode = 0;
187+
try {
188+
$client->testCacheConnection();
189+
} catch (BouncerException $e) {
190+
$errorMessage = $e->getMessage();
191+
$errorCode = $e->getCode();
192+
}
193+
194+
$this->assertEquals(101112, $errorCode);
195+
$this->assertEquals('Error while testing cache connection: unit test get cache storage', $errorMessage);
196+
}
197+
198+
}

tests/Unit/StandaloneBouncerTest.php

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -386,11 +386,6 @@ public function testPrivateAndProtectedMethods()
386386
$error,
387387
'Should have throw an error'
388388
);
389-
390-
391-
392-
393-
394389
}
395390

396391
}

0 commit comments

Comments
 (0)