forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSecurityCSRFSessionTest.php
More file actions
330 lines (259 loc) · 10.7 KB
/
SecurityCSRFSessionTest.php
File metadata and controls
330 lines (259 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Security;
use CodeIgniter\Config\Factories;
use CodeIgniter\Config\Services;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\SiteURI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Security\Exceptions\SecurityException;
use CodeIgniter\Session\Handlers\ArrayHandler;
use CodeIgniter\Session\Handlers\FileHandler;
use CodeIgniter\Session\Session;
use CodeIgniter\Superglobals;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Mock\MockAppConfig;
use CodeIgniter\Test\Mock\MockSession;
use CodeIgniter\Test\TestLogger;
use Config\App;
use Config\Cookie;
use Config\Logger as LoggerConfig;
use Config\Security as SecurityConfig;
use Config\Session as SessionConfig;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
/**
* @internal
*/
#[Group('SeparateProcess')]
#[PreserveGlobalState(false)]
#[RunTestsInSeparateProcesses]
final class SecurityCSRFSessionTest extends CIUnitTestCase
{
/**
* @var string CSRF protection hash
*/
private string $hash = '8b9218a55906f9dcc1dc263dce7f005a';
private SecurityConfig $config;
#[WithoutErrorHandler]
protected function setUp(): void
{
parent::setUp();
$_SESSION = [];
Factories::reset();
Services::injectMock('superglobals', new Superglobals());
$this->config = new SecurityConfig();
$this->config->csrfProtection = Security::CSRF_PROTECTION_SESSION;
Factories::injectMock('config', 'Security', $this->config);
$this->injectSession($this->hash);
}
private function createSession($options = []): Session
{
$defaults = [
'driver' => FileHandler::class,
'cookieName' => 'ci_session',
'expiration' => 7200,
'savePath' => '',
'matchIP' => false,
'timeToUpdate' => 300,
'regenerateDestroy' => false,
];
$config = array_merge($defaults, $options);
$sessionConfig = new SessionConfig();
foreach ($config as $key => $c) {
$sessionConfig->{$key} = $c;
}
$cookie = new Cookie();
foreach ([
'prefix' => '',
'domain' => '',
'path' => '/',
'secure' => false,
'samesite' => 'Lax',
] as $key => $value) {
$cookie->{$key} = $value;
}
Factories::injectMock('config', 'Cookie', $cookie);
$session = new MockSession(new ArrayHandler($sessionConfig, '127.0.0.1'), $sessionConfig);
$session->setLogger(new TestLogger(new LoggerConfig()));
return $session;
}
private function injectSession(string $hash): void
{
$session = $this->createSession();
$session->set('csrf_test_name', $hash);
Services::injectMock('session', $session);
}
private function createSecurity(): Security
{
return new Security($this->config);
}
public function testHashIsReadFromSession(): void
{
$security = $this->createSecurity();
$this->assertSame($this->hash, $security->getHash());
}
public function testCSRFVerifyPostThrowsExceptionOnNoMatch(): void
{
$this->expectException(SecurityException::class);
service('superglobals')
->setServer('REQUEST_METHOD', 'POST')
->setPost('csrf_test_name', '8b9218a55906f9dcc1dc263dce7f005b');
$request = $this->createIncomingRequest();
$security = $this->createSecurity();
$security->verify($request);
}
private function createIncomingRequest(?App $config = null): IncomingRequest
{
$config ??= new MockAppConfig();
return new IncomingRequest($config, new SiteURI($config), null, new UserAgent());
}
public function testCSRFVerifyPostReturnsSelfOnMatch(): void
{
service('superglobals')
->setServer('REQUEST_METHOD', 'POST')
->setPost('foo', 'bar')
->setPost('csrf_test_name', '8b9218a55906f9dcc1dc263dce7f005a');
$request = $this->createIncomingRequest();
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
$this->assertCount(1, service('superglobals')->getPostArray());
}
public function testCSRFVerifyPOSTHeaderThrowsExceptionOnNoMatch(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'POST');
$request = $this->createIncomingRequest();
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005b');
$security = $this->createSecurity();
$this->expectException(SecurityException::class);
$security->verify($request);
}
public function testCSRFVerifyPOSTHeaderReturnsSelfOnMatch(): void
{
service('superglobals')
->setServer('REQUEST_METHOD', 'POST')
->setPost('foo', 'bar');
$request = $this->createIncomingRequest();
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005a');
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
$this->assertCount(1, service('superglobals')->getPostArray());
}
public function testCSRFVerifyPUTHeaderThrowsExceptionOnNoMatch(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'PUT');
$request = $this->createIncomingRequest();
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005b');
$security = $this->createSecurity();
$this->expectException(SecurityException::class);
$security->verify($request);
}
public function testCSRFVerifyPUTHeaderReturnsSelfOnMatch(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'PUT');
$request = $this->createIncomingRequest();
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005a');
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
}
public function testCSRFVerifyPUTBodyReturnsSelfOnMatch(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'PUT');
$request = $this->createIncomingRequest();
$request->setBody('csrf_test_name=8b9218a55906f9dcc1dc263dce7f005a&foo=bar');
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
}
public function testCSRFVerifyJsonThrowsExceptionOnNoMatch(): void
{
$this->expectException(SecurityException::class);
service('superglobals')->setServer('REQUEST_METHOD', 'POST');
$request = $this->createIncomingRequest();
$request->setBody('{"csrf_test_name":"8b9218a55906f9dcc1dc263dce7f005b"}');
$security = $this->createSecurity();
$security->verify($request);
}
public function testCSRFVerifyJsonReturnsSelfOnMatch(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'POST');
$request = $this->createIncomingRequest();
$request->setBody('{"csrf_test_name":"8b9218a55906f9dcc1dc263dce7f005a","foo":"bar"}');
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
$this->assertSame('{"foo":"bar"}', $request->getBody());
}
public function testCSRFVerifyHeaderWithJsonBodyPreservesBody(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'POST');
$request = $this->createIncomingRequest();
$body = '{"foo":"bar"}';
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005a');
$request->setBody($body);
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
$this->assertSame($body, $request->getBody());
}
public function testCSRFVerifyHeaderWithJsonBodyStripsTokenFromBody(): void
{
service('superglobals')->setServer('REQUEST_METHOD', 'POST');
$request = $this->createIncomingRequest();
$request->setHeader('X-CSRF-TOKEN', '8b9218a55906f9dcc1dc263dce7f005a');
$request->setBody('{"csrf_test_name":"8b9218a55906f9dcc1dc263dce7f005a","foo":"bar"}');
$security = $this->createSecurity();
$this->assertInstanceOf(Security::class, $security->verify($request));
$this->assertLogged('info', 'CSRF token verified.');
$this->assertSame('{"foo":"bar"}', $request->getBody());
}
public function testRegenerateWithFalseSecurityRegenerateProperty(): void
{
service('superglobals')
->setServer('REQUEST_METHOD', 'POST')
->setPost('csrf_test_name', '8b9218a55906f9dcc1dc263dce7f005a');
/**
* @var SecurityConfig
*/
$config = Factories::config('Security');
$config->regenerate = false;
Factories::injectMock('config', 'Security', $config);
$request = $this->createIncomingRequest();
$security = $this->createSecurity();
$oldHash = $security->getHash();
$security->verify($request);
$newHash = $security->getHash();
$this->assertSame($oldHash, $newHash);
}
public function testRegenerateWithTrueSecurityRegenerateProperty(): void
{
service('superglobals')
->setServer('REQUEST_METHOD', 'POST')
->setPost('csrf_test_name', '8b9218a55906f9dcc1dc263dce7f005a');
/**
* @var SecurityConfig
*/
$config = Factories::config('Security');
$config->regenerate = true;
Factories::injectMock('config', 'Security', $config);
$request = $this->createIncomingRequest();
$security = $this->createSecurity();
$oldHash = $security->getHash();
$security->verify($request);
$newHash = $security->getHash();
$this->assertNotSame($oldHash, $newHash);
}
}