Skip to content

Commit c9bc915

Browse files
authored
Merge pull request #56 from crowdsecurity/feature/add-magento2-bouncer-php-lib-update
Feature/add magento2 bouncer php lib update
2 parents 2a891e8 + d05eb88 commit c9bc915

18 files changed

+585
-279
lines changed

composer.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@
3030
],
3131
"require": {
3232
"php": "^7.2 || ^8.0",
33-
"symfony/config": "^5.2",
33+
"symfony/config": "^4.4.27 || ^5.2",
3434
"symfony/cache": "^5.2",
35-
"monolog/monolog": "^2.1",
35+
"monolog/monolog": "^1.17 || ^2.1",
3636
"gregwar/captcha": "^1.1",
3737
"mlocati/ip-lib": "^1.14"
3838
},

composer.lock

Lines changed: 389 additions & 222 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

docker/php-8.0.Dockerfile

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ RUN apk update \
99
&& docker-php-source delete \
1010
&& docker-php-ext-install pdo_mysql \
1111
&& docker-php-ext-install gd \
12-
&& echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
12+
&& echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
1313
&& echo "xdebug.remote_autostart=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
14-
&& echo "xdebug.remote_port=9001" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
14+
&& echo "xdebug.client_port=9001" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
1515
&& echo "xdebug.remote_handler=dbgp" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
16-
&& echo "xdebug.remote_connect_back=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
16+
&& echo "xdebug.discover_client_host=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
1717
&& echo "xdebug.idekey=mertblog.net" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
18-
&& echo "xdebug.remote_host=docker.for.mac.localhost" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
18+
&& echo "xdebug.client_host=docker.for.mac.localhost" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
1919
&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
2020
&& rm -rf /tmp/*
2121

docs/complete-guide.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,15 @@ $cacheAdapter = new PhpFilesAdapter('', 0, __DIR__.'/.cache');
104104

105105
$requestedIp = $argv[1];
106106
if (!$requestedIp) {
107-
die('Usage: php check-ip.php <api_key>');
107+
die('Usage: php check-ip.php <IP>');
108108
}
109109

110110
// Init
111-
$bouncer = new Bouncer();
111+
$bouncer = new Bouncer($cacheAdapter);
112112
$bouncer->configure([
113113
'api_key' => getenv('BOUNCER_KEY'),
114114
'api_url' => 'http://crowdsec:8080'
115-
], $cacheAdapter
115+
]
116116
);
117117

118118
// Ask remediation to LAPI
@@ -267,7 +267,7 @@ $bouncer->configure([
267267
'api_key' => getenv('BOUNCER_KEY'),
268268
'api_url' => 'http://crowdsec:8080',
269269
'max_remediation_level' => 'captcha' // <== ADD THIS LINE!
270-
], $cacheAdapter
270+
]
271271
);
272272
```
273273

@@ -309,7 +309,7 @@ and replace these lines:
309309

310310
```php
311311
// Instanciate the bouncer
312-
$bouncer = new Bouncer();
312+
$bouncer = new Bouncer($cacheAdapter);
313313
```
314314

315315
with:
@@ -328,7 +328,7 @@ $fileHandler = new RotatingFileHandler(__DIR__.'/crowdsec.log', 0, Logger::WARNI
328328
$logger->pushHandler($fileHandler);
329329

330330
// Instanciate the bouncer
331-
$bouncer = new Bouncer($logger);
331+
$bouncer = new Bouncer($cacheAdapter, $logger);
332332
```
333333

334334
## Important note about cache expiration
@@ -371,12 +371,12 @@ use Monolog\Logger;
371371
$cacheAdapter = new MemcachedAdapter(MemcachedAdapter::createConnection('memcached://memcached:11211'));
372372

373373

374-
// Instanciate the Stream logger with info level(optional)
374+
// Instantiate the Stream logger with info level(optional)
375375
$logger = new Logger('example');
376376
$fileHandler = new RotatingFileHandler(__DIR__.'/crowdsec.log', 0, Logger::WARNING);
377377
$logger->pushHandler($fileHandler);
378378

379-
// Instanciate the bouncer
379+
// Instantiate the bouncer
380380
$bouncer = new Bouncer($cacheAdapter, $logger);
381381
$bouncer->configure([
382382
'api_key' => getenv('BOUNCER_KEY'),

docs/contribute.md

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,34 +10,38 @@ Here is the development environment for this library:
1010
## The guidelines
1111

1212
- We use TDD to code the library, with PHP Unit
13-
- CI via Github actions: run all tests over each PHP versions
14-
- Git workflow: [Github Flow](https://guides.github.com/introduction/flow/)
13+
- CI via GitHub actions: run all tests over each PHP versions
14+
- Git workflow: [GitHub Flow](https://guides.github.com/introduction/flow/)
1515
- PHP Source fully documented
1616
- Versioning system: Semver
1717
- Code coverage (not now)
1818
- Coding standards using [php-cs-fixer](https://cs.symfony.com/) configuration in **.php_cs**
1919

2020
## Run tests
2121

22-
First of all, install composer dependencies:
23-
24-
```bash
25-
docker-compose run app composer install
26-
```
27-
28-
Then run tests:
22+
Run tests with:
2923

3024
```bash
3125
./tests-local.sh # This will test with PHP 7.2 version
3226
```
3327

34-
Alternatively, you can tests with various php versions:
28+
Alternatively, you can test with various php versions:
3529

3630
```bash
3731
./tests-local-php7.3.sh
3832
./tests-local-php7.4.sh
3933
./tests-local-php8.0.sh
4034
```
35+
N.B: If you have a permission error message while launching these scripts, you should try to remove first the
36+
`var/docker-data` (if exists) folder and build the images separately:
37+
38+
```bash
39+
docker-compose build app
40+
docker-compose build app-php7.4
41+
docker-compose build app-php7.3
42+
docker-compose build app-php8.0
43+
```
44+
4145

4246
## How to lint the code
4347

docs/ddev.md

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# DDEV stack
2+
3+
There are many ways to install this library on a local PHP environment.
4+
5+
We are using [DDEV-Local](https://ddev.readthedocs.io/en/stable/) because it is quite simple to use and customize.
6+
7+
You may use your own local stack, but we provide here some useful tools that depends on DDEV.
8+
9+
10+
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
11+
12+
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
13+
14+
15+
## DDEV-Local setup
16+
17+
For a quick start, follow the below steps.
18+
19+
20+
### DDEV installation
21+
22+
Please follow the [official instructions](https://ddev.readthedocs.io/en/stable/#installation). On a Linux
23+
distribution, this should be as simple as
24+
25+
sudo apt-get install linuxbrew-wrapper
26+
brew tap drud/ddev && brew install ddev
27+
28+
29+
### Prepare DDEV PHP environment
30+
31+
The final structure of the project will look like below.
32+
33+
```
34+
php-project-sources
35+
36+
│ (your php project sources; could be a simple index.html file)
37+
38+
└───.ddev
39+
│ │
40+
│ │ (Cloned sources of a PHP specific ddev repo)
41+
42+
└───my-own-modules
43+
44+
45+
└───crowdsec-php-lib
46+
47+
│ (Clone of this repo)
48+
49+
```
50+
51+
- Create an empty folder that will contain all necessary sources:
52+
```
53+
mkdir php-project-sources
54+
```
55+
- Create an empty `.ddev` folder for DDEV and clone our pre-configured DDEV repo:
56+
57+
```
58+
mkdir php-project-sources/.ddev && cd php-project-sources/.ddev && git clone git@github.com:julienloizelet/ddev-php.
59+
git ./
60+
```
61+
- Copy some configurations file:
62+
63+
By default, ddev will launch a PHP 7.2 container. If you want to work with another PHP version, copy the
64+
corresponding config file. For example:
65+
66+
```
67+
cp .ddev/config_overrides/config.php74.yaml .ddev/config.php74.yaml
68+
```
69+
- Launch DDEV
70+
71+
```
72+
cd .ddev && ddev start
73+
```
74+
This should take some times on the first launch as this will download all necessary docker images.
75+
76+
77+
## Usage
78+
79+
80+
### Add CrowdSec bouncer and watcher
81+
82+
- To create a new bouncer in the crowdsec container, run:
83+
84+
```
85+
ddev create-bouncer [name]
86+
```
87+
88+
It will return the bouncer key.
89+
90+
- To create a new watcher, run:
91+
92+
```
93+
ddev create-watcher [name] [password]
94+
```
95+
96+
97+
### Use composer to update or install the lib
98+
99+
Run:
100+
101+
```
102+
ddev composer update --working-dir ./my-own-modules/crowdsec-php-lib
103+
```
104+
105+
### Unit test
106+
107+
First, create a bouncer and keep the result key.
108+
109+
```
110+
ddev create-bouncer
111+
```
112+
113+
Then, create a specific watcher for unit test:
114+
115+
```
116+
ddev create-watcher PhpUnitTestMachine PhpUnitTestMachinePassword
117+
```
118+
119+
Finally, run
120+
121+
122+
```
123+
ddev exec BOUNCER_KEY=your-bouncer-key LAPI_URL=http://crowdsec:8080 MEMCACHED_DSN=memcached://memcached:11211 REDIS_DSN=redis://redis:6379 /usr/bin/php ./my-own-modules/crowdsec-php-lib/vendor/bin/phpunit --testdox --colors --exclude-group ignore ./my-own-modules/crowdsec-php-lib/tests/IpVerificationTest.php
124+
```

examples/clear-cache.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@
2222
$logPath = __DIR__ . '/.crowdsec.log';
2323
$cachePath = __DIR__ . '/.cache';
2424

25-
// Instanciate a the "PhpFilesAdapter" cache adapter
25+
// Instantiate a the "PhpFilesAdapter" cache adapter
2626
// Note: to select another cache adapter (Memcached, Redis, ...), try other examples.
2727
$cacheAdapter = new Symfony\Component\Cache\Adapter\PhpFilesAdapter('', 0, $cachePath);
2828

29-
// Instanciate the Stream logger with info level(optional)
29+
// Instantiate the Stream logger with info level(optional)
3030
$logger = new Logger('example');
3131

3232
// Display logs with INFO verbosity
@@ -38,7 +38,7 @@
3838
$fileHandler = new RotatingFileHandler($logPath, 0, Logger::WARNING);
3939
$logger->pushHandler($fileHandler);
4040

41-
// Instanciate the bouncer
41+
// Instantiate the bouncer
4242
$bouncer = new Bouncer($cacheAdapter, $logger);
4343
$bouncer->configure(['api_key' => $bouncerApiKey, 'api_url' => $apiUrl]);
4444

scripts/publish-release.sh

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ git_base_dir=`git rev-parse --show-toplevel`
2121
# Update version everywhere (add and commit changes), tag and release
2222
git checkout main
2323
if [[ $platform == 'linux' ]]; then
24-
sed -i -E "s/v[0-9]+\.[0-9]+\.[0-9]/$NEW_GIT_VERSION/" $git_base_dir/src/Constants.php
24+
sed -i -E "s/v[0-9]+\.[0-9]+\.[0-9]+/$NEW_GIT_VERSION/" $git_base_dir/src/Constants.php
2525
else
26-
sed -i "" -E "s/v[0-9]+\.[0-9]+\.[0-9]/$NEW_GIT_VERSION/" $git_base_dir/src/Constants.php
26+
sed -i "" -E "s/v[0-9]+\.[0-9]+\.[0-9]+/$NEW_GIT_VERSION/" $git_base_dir/src/Constants.php
2727
fi
2828
git add $git_base_dir/src/Constants.php
2929

scripts/setup-local-crowdsec.sh

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
#!/bin/sh
22

3+
CONTAINER_NAME=${1:-app}
4+
35
# Delete existing LAPI database.
4-
[ -e ./var/docker-data/crowdsec.db ] && rm ./var/docker-data/crowdsec.db
6+
[ -e ./var/docker-data/crowdsec.db ] && docker-compose exec crowdsec rm -f /var/lib/crowdsec/data/crowdsec.db
57

68
# Start containers.
79
docker-compose up --force-recreate -d crowdsec
@@ -14,4 +16,4 @@ docker-compose exec crowdsec /usr/local/bin/cscli bouncers add bouncer-php-libra
1416
docker-compose exec crowdsec cscli machines add PhpUnitTestMachine --password PhpUnitTestMachinePassword > /dev/null 2>&1
1517

1618
# Ensure composer deps are presents
17-
docker-compose run app composer install
19+
docker-compose run $CONTAINER_NAME composer install

src/AbstractBounce.php

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ abstract class AbstractBounce
2929
/** @var bool */
3030
protected $debug = false;
3131

32+
/** @var bool */
33+
protected $displayErrors = false;
34+
3235
/** @var LoggerInterface */
3336
protected $logger;
3437

@@ -60,6 +63,11 @@ public function setDebug(bool $debug)
6063
$this->debug = $debug;
6164
}
6265

66+
public function setDisplayErrors(bool $displayErrors)
67+
{
68+
$this->displayErrors = $displayErrors;
69+
}
70+
6371
protected function initLoggerHelper($logDirectoryPath, $loggerName): void
6472
{
6573
// Singleton for this function
@@ -112,12 +120,12 @@ protected function bounceCurrentIp()
112120
$this->logger->warning('', [
113121
'type' => 'UNKNOWN_EXCEPTION_WHILE_BOUNCING',
114122
'ip' => $ip,
115-
'messsage' => $e->getMessage(),
123+
'message' => $e->getMessage(),
116124
'code' => $e->getCode(),
117125
'file' => $e->getFile(),
118126
'line' => $e->getLine(),
119127
]);
120-
if ($this->debug) {
128+
if ($this->displayErrors) {
121129
throw $e;
122130
}
123131
}
@@ -206,11 +214,14 @@ protected function handleCaptchaResolutionForm(string $ip)
206214
$this->getPostedVariable('phrase'),
207215
$ip)) {
208216
// User has correctly fill the captcha
209-
210217
$this->setSessionVariable('crowdsec_captcha_has_to_be_resolved', false);
211218
$this->unsetSessionVariable('crowdsec_captcha_phrase_to_guess');
212219
$this->unsetSessionVariable('crowdsec_captcha_inline_image');
213220
$this->unsetSessionVariable('crowdsec_captcha_resolution_failed');
221+
$redirect = $this->getSessionVariable('crowdsec_captcha_resolution_redirect')??'/';
222+
$this->unsetSessionVariable('crowdsec_captcha_resolution_redirect');
223+
header("Location: $redirect");
224+
exit(0);
214225
} else {
215226
// The user failed to resolve the captcha.
216227
$this->setSessionVariable('crowdsec_captcha_resolution_failed', true);
@@ -229,6 +240,9 @@ protected function handleCaptchaRemediation($ip)
229240
$this->storeNewCaptchaCoupleInSession();
230241
$this->setSessionVariable('crowdsec_captcha_has_to_be_resolved', true);
231242
$this->setSessionVariable('crowdsec_captcha_resolution_failed', false);
243+
$this->setSessionVariable('crowdsec_captcha_resolution_redirect', 'POST' === $this->getHttpMethod() &&
244+
!empty($_SERVER['HTTP_REFERER']) ?
245+
$_SERVER['HTTP_REFERER'] : $_SERVER['REQUEST_URI']);
232246
}
233247

234248
// Display captcha page if this is required.

0 commit comments

Comments
 (0)