Completed
Push — master ( df4949...df4068 )
by Joschi
03:25
created

HmacValidatorTest::atestRequestTimingValidation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 9.424
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * antibot
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Antibot
8
 * @subpackage Jkphl\Antibot\Tests\Ports
9
 * @author     Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2018 Joschi Kuphal <[email protected]>
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Antibot\Tests\Ports;
38
39
use Jkphl\Antibot\Infrastructure\Exceptions\HmacValidationException;
40
use Jkphl\Antibot\Infrastructure\Model\InputElement;
41
use Jkphl\Antibot\Ports\Validators\HmacValidator;
42
use Jkphl\Antibot\Tests\AbstractTestBase;
43
44
/**
45
 * HMAC Validator Test
46
 *
47
 * @package    Jkphl\Antibot
48
 * @subpackage Jkphl\Antibot\Tests\Ports
49
 */
50
class HmacValidatorTest extends AbstractTestBase
51
{
52
    /**
53
     * Protected function test the general HMAC validation
54
     *
55
     */
56
    public function testGeneralValidation(): void
57
    {
58
        $session       = md5(rand());
59
        $antibot       = $this->createAntibot($session);
60
        $hmacValidator = new HmacValidator();
61
        $antibot->addValidator($hmacValidator);
62
63
        // Run a first validation: Should be skipped
64
        $request1         = $this->createRequest(['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4']);
65
        $validationResult = $antibot->validate($request1);
66
        $this->assertFalse($validationResult->isValid());
67
        $this->assertFalse($validationResult->isFailed());
68
        $this->assertTrue($validationResult->isSkipped());
69
70
        // Arm & run a second request: Should succeed
71
        $armor            = $antibot->armor($request1, true);
72
        $post             = $this->getArmorParams($armor);
0 ignored issues
show
Bug introduced by
It seems like $armor defined by $antibot->armor($request1, true) on line 71 can also be of type string; however, Jkphl\Antibot\Tests\Port...rTest::getArmorParams() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
73
        $request2         = $this->createRequest(['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
74
        $validationResult = $antibot->validate($request2);
75
        $this->assertTrue($validationResult->isValid());
76
    }
77
78
    /**
79
     * Protected function test the HMAC request method order validation
80
     */
81
    public function testRequestMethodOrderValidation(): void
82
    {
83
        $session       = md5(rand());
84
        $antibot       = $this->createAntibot($session);
85
        $hmacValidator = new HmacValidator();
86
        $hmacValidator->setMethodVector(HmacValidator::METHOD_GET, HmacValidator::METHOD_POST);
87
        $antibot->addValidator($hmacValidator);
88
        $request1 = $this->createRequest(['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4']);
89
        $armor    = $antibot->armor($request1, true);
90
        $post     = $this->getArmorParams($armor);
0 ignored issues
show
Bug introduced by
It seems like $armor defined by $antibot->armor($request1, true) on line 89 can also be of type string; however, Jkphl\Antibot\Tests\Port...rTest::getArmorParams() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
91
92
        // Second request
93
        $request2         = $this->createRequest(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
94
        $validationResult = $antibot->validate($request2);
95
        $this->assertTrue($validationResult->isValid());
96
97
        // Third request using the wrong request method
98
        $request3         = $this->createRequest(['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
99
        $validationResult = $antibot->validate($request3);
100
        $this->assertFalse($validationResult->isValid());
101
        $this->assertTrue($validationResult->hasErrors());
102
        $errors = $validationResult->getErrors();
103
        $this->assertEquals(1, count($errors));
104
        $this->assertInstanceOf(HmacValidationException::class, $errors[0]);
105
        $this->assertEquals(1544292604, $errors[0]->getCode());
106
    }
107
108
    /**
109
     * Protected function test the HMAC request timing validation
110
     */
111
    public function testRequestTimingValidation(): void
112
    {
113
        $session       = md5(rand());
114
        $antibot       = $this->createAntibot($session);
115
        $hmacValidator = new HmacValidator();
116
        $hmacValidator->setSubmissionTimes(10, 5, 1);
117
        $antibot->addValidator($hmacValidator);
118
        $request1 = $this->createRequest(['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4']);
119
        $this->assertTrue($antibot->validate($request1)->isSkipped());
120
121
        // Create the armor for a second request, including submission time limits
122
        $armor = $antibot->armor($request1, true);
123
        $post  = $this->getArmorParams($armor);
0 ignored issues
show
Bug introduced by
It seems like $armor defined by $antibot->armor($request1, true) on line 122 can also be of type string; however, Jkphl\Antibot\Tests\Port...rTest::getArmorParams() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
124
125
        // A second call after only 1 second should fail validation
126
        sleep(1);
127
        $request2         = $this->createRequest(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
128
        $validationResult = $antibot->validate($request2);
129
        $this->assertTrue($validationResult->isFailed());
130
131
        // Waiting for 4 more seconds should succeed
132
        sleep(5);
133
        $request3         = $this->createRequest(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
134
        $validationResult = $antibot->validate($request3);
135
        $this->assertTrue($validationResult->isValid());
136
137
        // Rearm, wait for 1 second and retry: Should succeed as it's a follow-up request
138
        $armor = $antibot->armor($request3, true);
139
        $post  = $this->getArmorParams($armor);
0 ignored issues
show
Bug introduced by
It seems like $armor defined by $antibot->armor($request3, true) on line 138 can also be of type string; however, Jkphl\Antibot\Tests\Port...rTest::getArmorParams() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
140
        sleep(1);
141
        $request4         = $this->createRequest(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
142
        $validationResult = $antibot->validate($request4);
143
        $this->assertTrue($validationResult->isValid());
144
145
        // Wait for another 10 seconds and retry: Should fail as it exceeded the maximum time
146
        sleep(10);
147
        $request5         = $this->createRequest(['REQUEST_METHOD' => 'POST', 'REMOTE_ADDR' => '1.2.3.4'], [], $post);
148
        $validationResult = $antibot->validate($request5);
149
        $this->assertTrue($validationResult->isFailed());
150
        $this->assertTrue($validationResult->hasErrors());
151
        $errors = $validationResult->getErrors();
152
        $this->assertEquals(1, count($errors));
153
        $this->assertInstanceOf(HmacValidationException::class, $errors[0]);
154
        $this->assertEquals(1544292684, $errors[0]->getCode());
155
    }
156
157
    /**
158
     * Test the armoring
159
     */
160
    public function testArmor(): void
161
    {
162
        $sessionId     = md5(rand());
163
        $antibot       = $this->createAntibot($sessionId);
164
        $request       = $this->createRequest(
165
            ['REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '1.2.3.4'],
166
            ['name' => 'John Doe', 'email' => '[email protected]']
167
        );
168
        $hmacValidator = new HmacValidator();
169
        $hmacValidator->setMethodVector(HmacValidator::METHOD_GET, HmacValidator::METHOD_POST);
170
        $hmacValidator->setSubmissionTimes(1800, 10, 3);
171
        $antibot->addValidator($hmacValidator);
172
        $armor = $antibot->armor($request, true);
173
        $this->assertTrue(is_array($armor));
174
        $this->assertEquals(2, count($armor));
175
        $this->assertEquals(40, strlen($armor[0]->getAttributes()['value']));
176
        $this->assertTrue(is_int($armor[1]->getAttributes()['value']));
177
    }
178
179
    /**
180
     * Translate armor input elements to GET / POST parameters
181
     *
182
     * @param array $armor Armor input elements
183
     *
184
     * @return array GET / POST Parameters
185
     */
186
    protected function getArmorParams(array $armor): array
187
    {
188
        // Prepare the second call
189
        $params = [];
190
        /** @var InputElement $input */
191
        foreach ($armor as $input) {
192
            $inputAttrs                  = $input->getAttributes();
193
            $params[$inputAttrs['name']] = $inputAttrs['value'];
194
        }
195
        parse_str(http_build_query($params), $params);
196
197
        return $params;
198
    }
199
}
200