File: SameOriginCsrfTokenManagerTest.php

package info (click to toggle)
symfony 7.3.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 147,804 kB
  • sloc: php: 1,506,509; xml: 6,816; javascript: 1,043; sh: 586; makefile: 241; pascal: 70
file content (259 lines) | stat: -rw-r--r-- 10,363 bytes parent folder | download
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
<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Csrf\Tests;

use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\SameOriginCsrfTokenManager;

class SameOriginCsrfTokenManagerTest extends TestCase
{
    private $requestStack;
    private $logger;
    private $csrfTokenManager;

    protected function setUp(): void
    {
        $this->requestStack = new RequestStack();
        $this->logger = $this->createMock(LoggerInterface::class);
        $this->csrfTokenManager = new SameOriginCsrfTokenManager($this->requestStack, $this->logger);
    }

    public function testInvalidCookieName()
    {
        $this->expectException(\InvalidArgumentException::class);
        new SameOriginCsrfTokenManager($this->requestStack, $this->logger, null, [], SameOriginCsrfTokenManager::CHECK_NO_HEADER, '');
    }

    public function testInvalidCookieNameCharacters()
    {
        $this->expectException(\InvalidArgumentException::class);
        new SameOriginCsrfTokenManager($this->requestStack, $this->logger, null, [], SameOriginCsrfTokenManager::CHECK_NO_HEADER, 'invalid name!');
    }

    public function testGetToken()
    {
        $tokenId = 'test_token';
        $token = $this->csrfTokenManager->getToken($tokenId);

        $this->assertInstanceOf(CsrfToken::class, $token);
        $this->assertSame($tokenId, $token->getId());
    }

    public function testNoRequest()
    {
        $token = new CsrfToken('test_token', 'test_value');

        $this->logger->expects($this->once())->method('error')->with('CSRF validation failed: No request found.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testInvalidTokenLength()
    {
        $request = new Request();
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', '');

        $this->logger->expects($this->once())->method('warning')->with('Invalid double-submit CSRF token.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testInvalidOrigin()
    {
        $request = new Request();
        $request->headers->set('Origin', 'http://malicious.com');
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $this->logger->expects($this->once())->method('warning')->with('CSRF validation failed: origin info doesn\'t match.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testValidOrigin()
    {
        $request = new Request();
        $request->headers->set('Origin', $request->getSchemeAndHttpHost());
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $this->logger->expects($this->once())->method('debug')->with('CSRF validation accepted using origin info.');
        $this->assertTrue($this->csrfTokenManager->isTokenValid($token));
        $this->assertSame(1 << 8, $request->attributes->get('csrf-token'));
    }

    public function testValidRefererInvalidOrigin()
    {
        $request = new Request();
        $request->headers->set('Origin', 'http://localhost:1234');
        $request->headers->set('Referer', $request->getSchemeAndHttpHost());
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $this->logger->expects($this->once())->method('debug')->with('CSRF validation accepted using origin info.');
        $this->assertTrue($this->csrfTokenManager->isTokenValid($token));
        $this->assertSame(1 << 8, $request->attributes->get('csrf-token'));
    }

    public function testValidOriginAfterDoubleSubmit()
    {
        $session = $this->createMock(Session::class);
        $request = new Request();
        $request->setSession($session);
        $request->headers->set('Origin', $request->getSchemeAndHttpHost());
        $request->cookies->set('sess', 'id');
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $session->expects($this->once())->method('getName')->willReturn('sess');
        $session->expects($this->once())->method('get')->with('csrf-token')->willReturn(2 << 8);
        $this->logger->expects($this->once())->method('warning')->with('CSRF validation failed: double-submit info was used in a previous request but is now missing.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testMissingPreviousOrigin()
    {
        $session = $this->createMock(Session::class);
        $request = new Request();
        $request->cookies->set('csrf-token_'.str_repeat('a', 24), 'csrf-token');
        $request->setSession($session);
        $request->cookies->set('sess', 'id');
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $session->expects($this->once())->method('getName')->willReturn('sess');
        $session->expects($this->once())->method('get')->with('csrf-token')->willReturn(1 << 8);
        $this->logger->expects($this->once())->method('warning')->with('CSRF validation failed: origin info was used in a previous request but is now missing.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testValidDoubleSubmit()
    {
        $request = new Request();
        $request->cookies->set('csrf-token_'.str_repeat('a', 24), 'csrf-token');
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $this->logger->expects($this->once())->method('debug')->with('CSRF validation accepted using double-submit info.');
        $this->assertTrue($this->csrfTokenManager->isTokenValid($token));
        $this->assertSame(2 << 8, $request->attributes->get('csrf-token'));
    }

    public function testCheckOnlyHeader()
    {
        $csrfTokenManager = new SameOriginCsrfTokenManager($this->requestStack, $this->logger, null, [], SameOriginCsrfTokenManager::CHECK_ONLY_HEADER);

        $request = new Request();
        $tokenValue = str_repeat('a', 24);
        $request->headers->set('csrf-token', $tokenValue);
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', $tokenValue);

        $this->logger->expects($this->once())->method('debug')->with('CSRF validation accepted using double-submit info.');
        $this->assertTrue($csrfTokenManager->isTokenValid($token));
        $this->assertSame('csrf-token', $request->cookies->get('csrf-token_'.$tokenValue));

        $this->logger->expects($this->once())->method('warning')->with('CSRF validation failed: wrong token found in header info.');
        $this->assertFalse($csrfTokenManager->isTokenValid(new CsrfToken('test_token', str_repeat('b', 24))));
    }

    #[\PHPUnit\Framework\Attributes\TestWith([0])]
    #[\PHPUnit\Framework\Attributes\TestWith([1])]
    #[\PHPUnit\Framework\Attributes\TestWith([2])]
    public function testValidOriginMissingDoubleSubmit(int $checkHeader)
    {
        $csrfTokenManager = new SameOriginCsrfTokenManager($this->requestStack, $this->logger, null, [], $checkHeader);

        $request = new Request();
        $tokenValue = str_repeat('a', 24);
        $request->headers->set('Origin', $request->getSchemeAndHttpHost());
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', $tokenValue);

        $this->logger->expects($this->once())->method('debug')->with('CSRF validation accepted using origin info.');
        $this->assertTrue($csrfTokenManager->isTokenValid($token));
    }

    public function testMissingEverything()
    {
        $request = new Request();
        $this->requestStack->push($request);

        $token = new CsrfToken('test_token', str_repeat('a', 24));

        $this->logger->expects($this->once())->method('warning')->with('CSRF validation failed: double-submit and origin info not found.');
        $this->assertFalse($this->csrfTokenManager->isTokenValid($token));
    }

    public function testClearCookies()
    {
        $request = new Request([], [], ['csrf-token' => 2], ['csrf-token_test' => 'csrf-token']);
        $response = new Response();

        $this->csrfTokenManager->clearCookies($request, $response);

        $this->assertTrue($response->headers->has('Set-Cookie'));
    }

    public function testPersistStrategyWithStartedSession()
    {
        $session = $this->createMock(Session::class);
        $session->method('isStarted')->willReturn(true);

        $request = new Request();
        $request->setSession($session);
        $request->attributes->set('csrf-token', 2 << 8);

        $session->expects($this->once())->method('set')->with('csrf-token', 2 << 8);

        $this->csrfTokenManager->persistStrategy($request);
    }

    public function testPersistStrategyWithSessionNotStarted()
    {
        $session = $this->createMock(Session::class);

        $request = new Request();
        $request->setSession($session);
        $request->attributes->set('csrf-token', 2 << 8);

        $session->expects($this->never())->method('set');

        $this->csrfTokenManager->persistStrategy($request);
    }

    public function testOnKernelResponse()
    {
        $request = new Request([], [], ['csrf-token' => 2], ['csrf-token_test' => 'csrf-token']);
        $response = new Response();
        $event = new ResponseEvent($this->createMock(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, $response);

        $this->csrfTokenManager->onKernelResponse($event);

        $this->assertTrue($response->headers->has('Set-Cookie'));
    }
}