CsrfProtectionMiddlewareTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. * @link http://cakephp.org CakePHP(tm) Project
  13. * @since 3.5.0
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Http\Middleware;
  17. use Cake\Http\Cookie\Cookie;
  18. use Cake\Http\Cookie\CookieInterface;
  19. use Cake\Http\Exception\InvalidCsrfTokenException;
  20. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  21. use Cake\Http\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\TestSuite\TestCase;
  24. use Cake\Utility\Security;
  25. use Laminas\Diactoros\Response as DiactorosResponse;
  26. use Laminas\Diactoros\Response\RedirectResponse;
  27. use Psr\Http\Message\ServerRequestInterface;
  28. use Psr\Http\Server\RequestHandlerInterface;
  29. use RuntimeException;
  30. use TestApp\Http\TestRequestHandler;
  31. /**
  32. * Test for CsrfProtection
  33. */
  34. class CsrfProtectionMiddlewareTest extends TestCase
  35. {
  36. protected function createOldToken(): string
  37. {
  38. // Create an old style token. These tokens are hexadecimal with an hmac.
  39. $random = Security::randomString(CsrfProtectionMiddleware::TOKEN_VALUE_LENGTH);
  40. return $random . hash_hmac('sha1', $random, Security::getSalt());
  41. }
  42. /**
  43. * Data provider for HTTP method tests.
  44. *
  45. * HEAD and GET do not populate $_POST or request->data.
  46. *
  47. * @return array
  48. */
  49. public static function safeHttpMethodProvider(): array
  50. {
  51. return [
  52. ['GET'],
  53. ['HEAD'],
  54. ];
  55. }
  56. /**
  57. * Data provider for HTTP methods that can contain request bodies.
  58. *
  59. * @return array
  60. */
  61. public static function httpMethodProvider(): array
  62. {
  63. return [
  64. ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD'],
  65. ];
  66. }
  67. /**
  68. * Provides the request handler
  69. */
  70. protected function _getRequestHandler(): RequestHandlerInterface
  71. {
  72. return new TestRequestHandler(function () {
  73. return new Response();
  74. });
  75. }
  76. /**
  77. * Test setting the cookie value
  78. */
  79. public function testSettingCookie(): void
  80. {
  81. $request = new ServerRequest([
  82. 'environment' => ['REQUEST_METHOD' => 'GET'],
  83. 'webroot' => '/dir/',
  84. ]);
  85. /** @var \Cake\Http\ServerRequest $updatedRequest */
  86. $updatedRequest = null;
  87. $handler = new TestRequestHandler(function ($request) use (&$updatedRequest) {
  88. $updatedRequest = $request;
  89. return new Response();
  90. });
  91. $middleware = new CsrfProtectionMiddleware();
  92. $response = $middleware->process($request, $handler);
  93. $cookie = $response->getCookie('csrfToken');
  94. $this->assertNotEmpty($cookie, 'Should set a token.');
  95. $this->assertMatchesRegularExpression('/^[a-z0-9\/+]+={0,2}$/i', $cookie['value'], 'Should look like base64.');
  96. $this->assertSame(0, $cookie['expires'], 'session duration.');
  97. $this->assertSame('/dir/', $cookie['path'], 'session path.');
  98. $requestAttr = $updatedRequest->getAttribute('csrfToken');
  99. $this->assertNotEquals($cookie['value'], $requestAttr);
  100. $this->assertEquals(strlen($cookie['value']) * 2, strlen($requestAttr));
  101. $this->assertMatchesRegularExpression('/^[A-Z0-9\/+]+=*$/i', $requestAttr);
  102. }
  103. /**
  104. * Test setting request attribute based on old cookie value.
  105. */
  106. public function testRequestAttributeCompatWithOldToken(): void
  107. {
  108. $middleware = new CsrfProtectionMiddleware();
  109. $oldToken = $this->createOldToken();
  110. $request = new ServerRequest([
  111. 'environment' => [
  112. 'REQUEST_METHOD' => 'GET',
  113. ],
  114. 'cookies' => ['csrfToken' => $oldToken],
  115. ]);
  116. /** @var \Cake\Http\ServerRequest $updatedRequest */
  117. $updatedRequest = null;
  118. $handler = new TestRequestHandler(function ($request) use (&$updatedRequest) {
  119. $updatedRequest = $request;
  120. return new Response();
  121. });
  122. $response = $middleware->process($request, $handler);
  123. $this->assertInstanceOf(Response::class, $response);
  124. $requestAttr = $updatedRequest->getAttribute('csrfToken');
  125. $this->assertSame($requestAttr, $oldToken, 'Request attribute should match the token.');
  126. }
  127. /**
  128. * Test that the CSRF tokens are not required for idempotent operations
  129. *
  130. * @dataProvider safeHttpMethodProvider
  131. */
  132. public function testSafeMethodNoCsrfRequired(string $method): void
  133. {
  134. $request = new ServerRequest([
  135. 'environment' => [
  136. 'REQUEST_METHOD' => $method,
  137. 'HTTP_X_CSRF_TOKEN' => 'nope',
  138. ],
  139. 'cookies' => ['csrfToken' => 'testing123'],
  140. ]);
  141. // No exception means the test is valid
  142. $middleware = new CsrfProtectionMiddleware();
  143. $response = $middleware->process($request, $this->_getRequestHandler());
  144. $this->assertInstanceOf(Response::class, $response);
  145. }
  146. /**
  147. * Test that the CSRF tokens are regenerated when token is not valid
  148. *
  149. * @return void
  150. */
  151. public function testRegenerateTokenOnGetWithInvalidData()
  152. {
  153. $request = new ServerRequest([
  154. 'environment' => [
  155. 'REQUEST_METHOD' => 'GET',
  156. ],
  157. 'cookies' => ['csrfToken' => "\x20\x26"],
  158. ]);
  159. $middleware = new CsrfProtectionMiddleware();
  160. /** @var \Cake\Http\Response $response */
  161. $response = $middleware->process($request, $this->_getRequestHandler());
  162. $this->assertInstanceOf(Response::class, $response);
  163. $this->assertGreaterThan(32, strlen($response->getCookie('csrfToken')['value']));
  164. }
  165. /**
  166. * Test that the CSRF tokens are set for redirect responses
  167. */
  168. public function testRedirectResponseCookies(): void
  169. {
  170. $request = new ServerRequest([
  171. 'environment' => ['REQUEST_METHOD' => 'GET'],
  172. ]);
  173. $handler = new TestRequestHandler(function () {
  174. return new RedirectResponse('/');
  175. });
  176. $middleware = new CsrfProtectionMiddleware();
  177. $response = $middleware->process($request, $handler);
  178. $this->assertStringContainsString('csrfToken=', $response->getHeaderLine('Set-Cookie'));
  179. }
  180. /**
  181. * Test that double applying CSRF causes a failure.
  182. */
  183. public function testDoubleApplicationFailure(): void
  184. {
  185. $request = new ServerRequest([
  186. 'environment' => ['REQUEST_METHOD' => 'GET'],
  187. ]);
  188. $request = $request->withAttribute('csrfToken', 'not-good');
  189. $handler = new TestRequestHandler(function () {
  190. return new RedirectResponse('/');
  191. });
  192. $middleware = new CsrfProtectionMiddleware();
  193. $this->expectException(RuntimeException::class);
  194. $middleware->process($request, $handler);
  195. }
  196. /**
  197. * Test that the CSRF tokens are set for diactoros responses
  198. */
  199. public function testDiactorosResponseCookies(): void
  200. {
  201. $request = new ServerRequest([
  202. 'environment' => ['REQUEST_METHOD' => 'GET'],
  203. ]);
  204. $handler = new TestRequestHandler(function () {
  205. return new DiactorosResponse();
  206. });
  207. $middleware = new CsrfProtectionMiddleware();
  208. $response = $middleware->process($request, $handler);
  209. $this->assertStringContainsString('csrfToken=', $response->getHeaderLine('Set-Cookie'));
  210. }
  211. /**
  212. * Test that the X-CSRF-Token works with the various http methods.
  213. *
  214. * @dataProvider httpMethodProvider
  215. */
  216. public function testValidTokenInHeaderCompat(string $method): void
  217. {
  218. $middleware = new CsrfProtectionMiddleware();
  219. $token = $middleware->createToken();
  220. $request = new ServerRequest([
  221. 'environment' => [
  222. 'REQUEST_METHOD' => $method,
  223. 'HTTP_X_CSRF_TOKEN' => $token,
  224. ],
  225. 'post' => ['a' => 'b'],
  226. 'cookies' => ['csrfToken' => $token],
  227. ]);
  228. $response = new Response();
  229. // No exception means the test is valid
  230. $response = $middleware->process($request, $this->_getRequestHandler());
  231. $this->assertInstanceOf(Response::class, $response);
  232. }
  233. /**
  234. * Test that the X-CSRF-Token works with the various http methods.
  235. *
  236. * @dataProvider httpMethodProvider
  237. */
  238. public function testValidTokenInHeader(string $method): void
  239. {
  240. $middleware = new CsrfProtectionMiddleware();
  241. $token = $middleware->createToken();
  242. $salted = $middleware->saltToken($token);
  243. $request = new ServerRequest([
  244. 'environment' => [
  245. 'REQUEST_METHOD' => $method,
  246. 'HTTP_X_CSRF_TOKEN' => $salted,
  247. ],
  248. 'post' => ['a' => 'b'],
  249. 'cookies' => ['csrfToken' => $token],
  250. ]);
  251. $response = new Response();
  252. // No exception means the test is valid
  253. $response = $middleware->process($request, $this->_getRequestHandler());
  254. $this->assertInstanceOf(Response::class, $response);
  255. }
  256. /**
  257. * Test that the X-CSRF-Token works with the various http methods.
  258. *
  259. * @dataProvider httpMethodProvider
  260. */
  261. public function testInvalidTokenInHeader(string $method): void
  262. {
  263. $request = new ServerRequest([
  264. 'environment' => [
  265. 'REQUEST_METHOD' => $method,
  266. 'HTTP_X_CSRF_TOKEN' => 'nope',
  267. ],
  268. 'post' => ['a' => 'b'],
  269. 'cookies' => ['csrfToken' => 'testing123'],
  270. ]);
  271. $middleware = new CsrfProtectionMiddleware();
  272. try {
  273. $middleware->process($request, $this->_getRequestHandler());
  274. $this->fail();
  275. } catch (InvalidCsrfTokenException $exception) {
  276. $responseHeaders = $exception->getHeaders();
  277. $this->assertArrayHasKey('Set-Cookie', $responseHeaders);
  278. $cookie = Cookie::createFromHeaderString($responseHeaders['Set-Cookie']);
  279. $this->assertSame('csrfToken', $cookie->getName(), 'Should automatically delete cookie with invalid CSRF token');
  280. $this->assertTrue($cookie->isExpired(), 'Should automatically delete cookie with invalid CSRF token');
  281. }
  282. }
  283. /**
  284. * Test that request data works with the various http methods.
  285. *
  286. * @dataProvider httpMethodProvider
  287. */
  288. public function testValidTokenRequestDataCompat(string $method): void
  289. {
  290. $middleware = new CsrfProtectionMiddleware();
  291. $token = $this->createOldToken();
  292. $request = new ServerRequest([
  293. 'environment' => [
  294. 'REQUEST_METHOD' => $method,
  295. ],
  296. 'post' => ['_csrfToken' => $token],
  297. 'cookies' => ['csrfToken' => $token],
  298. ]);
  299. $handler = new TestRequestHandler(function ($request) {
  300. $this->assertNull($request->getData('_csrfToken'));
  301. return new Response();
  302. });
  303. // No exception means everything is OK
  304. $middleware->process($request, $handler);
  305. }
  306. /**
  307. * Test that request data works with the various http methods.
  308. *
  309. * @dataProvider httpMethodProvider
  310. */
  311. public function testValidTokenRequestDataSalted(string $method): void
  312. {
  313. $middleware = new CsrfProtectionMiddleware();
  314. $token = $middleware->createToken();
  315. $salted = $middleware->saltToken($token);
  316. $request = new ServerRequest([
  317. 'environment' => [
  318. 'REQUEST_METHOD' => $method,
  319. ],
  320. 'post' => ['_csrfToken' => $salted],
  321. 'cookies' => ['csrfToken' => $token],
  322. ]);
  323. $handler = new TestRequestHandler(function ($request) {
  324. $this->assertNull($request->getData('_csrfToken'));
  325. return new Response();
  326. });
  327. // No exception means everything is OK
  328. $middleware->process($request, $handler);
  329. }
  330. /**
  331. * Test that invalid string cookies are rejected.
  332. *
  333. * @return void
  334. */
  335. public function testInvalidTokenStringCookies()
  336. {
  337. $this->expectException(InvalidCsrfTokenException::class);
  338. $request = new ServerRequest([
  339. 'environment' => [
  340. 'REQUEST_METHOD' => 'POST',
  341. ],
  342. 'post' => ['_csrfToken' => ["\x20\x26"]],
  343. 'cookies' => ['csrfToken' => ["\x20\x26"]],
  344. ]);
  345. $middleware = new CsrfProtectionMiddleware();
  346. $middleware->process($request, $this->_getRequestHandler());
  347. }
  348. /**
  349. * Test that request non string cookies are ignored.
  350. */
  351. public function testInvalidTokenNonStringCookies(): void
  352. {
  353. $this->expectException(InvalidCsrfTokenException::class);
  354. $request = new ServerRequest([
  355. 'environment' => [
  356. 'REQUEST_METHOD' => 'POST',
  357. ],
  358. 'post' => ['_csrfToken' => ['nope']],
  359. 'cookies' => ['csrfToken' => ['nope']],
  360. ]);
  361. $middleware = new CsrfProtectionMiddleware();
  362. $middleware->process($request, $this->_getRequestHandler());
  363. }
  364. /**
  365. * Test that request data works with the various http methods.
  366. *
  367. * @dataProvider httpMethodProvider
  368. */
  369. public function testInvalidTokenRequestData(string $method): void
  370. {
  371. $request = new ServerRequest([
  372. 'environment' => [
  373. 'REQUEST_METHOD' => $method,
  374. ],
  375. 'post' => ['_csrfToken' => 'nope'],
  376. 'cookies' => ['csrfToken' => 'testing123'],
  377. ]);
  378. $middleware = new CsrfProtectionMiddleware();
  379. try {
  380. $middleware->process($request, $this->_getRequestHandler());
  381. $this->fail();
  382. } catch (InvalidCsrfTokenException $exception) {
  383. $responseHeaders = $exception->getHeaders();
  384. $this->assertArrayHasKey('Set-Cookie', $responseHeaders);
  385. $cookie = Cookie::createFromHeaderString($responseHeaders['Set-Cookie']);
  386. $this->assertSame('csrfToken', $cookie->getName(), 'Should automatically delete cookie with invalid CSRF token');
  387. $this->assertTrue($cookie->isExpired(), 'Should automatically delete cookie with invalid CSRF token');
  388. }
  389. }
  390. /**
  391. * Test that tokens cannot be simple matches and must pass our hmac.
  392. */
  393. public function testInvalidTokenIncorrectOrigin(): void
  394. {
  395. $request = new ServerRequest([
  396. 'environment' => [
  397. 'REQUEST_METHOD' => 'POST',
  398. ],
  399. 'post' => ['_csrfToken' => 'this is a match'],
  400. 'cookies' => ['csrfToken' => 'this is a match'],
  401. ]);
  402. $middleware = new CsrfProtectionMiddleware();
  403. $this->expectException(InvalidCsrfTokenException::class);
  404. $middleware->process($request, $this->_getRequestHandler());
  405. }
  406. /**
  407. * Test that missing post field fails
  408. */
  409. public function testInvalidTokenRequestDataMissing(): void
  410. {
  411. $request = new ServerRequest([
  412. 'environment' => [
  413. 'REQUEST_METHOD' => 'POST',
  414. ],
  415. 'post' => [],
  416. 'cookies' => ['csrfToken' => 'testing123'],
  417. ]);
  418. $middleware = new CsrfProtectionMiddleware();
  419. $this->expectException(InvalidCsrfTokenException::class);
  420. $middleware->process($request, $this->_getRequestHandler());
  421. }
  422. /**
  423. * Test that missing header and cookie fails
  424. *
  425. * @dataProvider httpMethodProvider
  426. */
  427. public function testInvalidTokenMissingCookie(string $method): void
  428. {
  429. $request = new ServerRequest([
  430. 'environment' => [
  431. 'REQUEST_METHOD' => $method,
  432. ],
  433. 'post' => ['_csrfToken' => 'could-be-valid'],
  434. 'cookies' => [],
  435. ]);
  436. $middleware = new CsrfProtectionMiddleware();
  437. try {
  438. $middleware->process($request, $this->_getRequestHandler());
  439. $this->fail();
  440. } catch (InvalidCsrfTokenException $exception) {
  441. $responseHeaders = $exception->getHeaders();
  442. $this->assertEmpty($responseHeaders, 'Should not send any header');
  443. }
  444. }
  445. /**
  446. * Test that the configuration options work.
  447. */
  448. public function testConfigurationCookieCreate(): void
  449. {
  450. $request = new ServerRequest([
  451. 'environment' => ['REQUEST_METHOD' => 'GET'],
  452. 'webroot' => '/dir/',
  453. ]);
  454. $middleware = new CsrfProtectionMiddleware([
  455. 'cookieName' => 'token',
  456. 'expiry' => '+1 hour',
  457. 'secure' => true,
  458. 'httponly' => true,
  459. 'samesite' => CookieInterface::SAMESITE_STRICT,
  460. ]);
  461. $response = $middleware->process($request, $this->_getRequestHandler());
  462. $this->assertEmpty($response->getCookie('csrfToken'));
  463. $cookie = $response->getCookie('token');
  464. $this->assertNotEmpty($cookie, 'Should set a token.');
  465. $this->assertMatchesRegularExpression('/^[a-z0-9\/+]+={0,2}$/i', $cookie['value'], 'Should look like base64.');
  466. $this->assertWithinRange(strtotime('+1 hour'), $cookie['expires'], 1, 'session duration.');
  467. $this->assertSame('/dir/', $cookie['path'], 'session path.');
  468. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  469. $this->assertTrue($cookie['httponly'], 'cookie httponly flag missing');
  470. $this->assertSame(CookieInterface::SAMESITE_STRICT, $cookie['samesite'], 'samesite attribute missing');
  471. }
  472. /**
  473. * Test that the configuration options work.
  474. *
  475. * There should be no exception thrown.
  476. */
  477. public function testConfigurationValidate(): void
  478. {
  479. $middleware = new CsrfProtectionMiddleware([
  480. 'cookieName' => 'token',
  481. 'field' => 'token',
  482. 'expiry' => 90,
  483. ]);
  484. $token = $middleware->createToken();
  485. $request = new ServerRequest([
  486. 'environment' => ['REQUEST_METHOD' => 'POST'],
  487. 'cookies' => ['csrfToken' => 'nope', 'token' => $token],
  488. 'post' => ['_csrfToken' => 'no match', 'token' => $token],
  489. ]);
  490. $response = new Response();
  491. $response = $middleware->process($request, $this->_getRequestHandler());
  492. $this->assertInstanceOf(Response::class, $response);
  493. }
  494. public function testSkippingTokenCheckUsingSkipCheckCallback(): void
  495. {
  496. $request = new ServerRequest([
  497. 'post' => [
  498. '_csrfToken' => 'foo',
  499. ],
  500. 'environment' => [
  501. 'REQUEST_METHOD' => 'POST',
  502. ],
  503. ]);
  504. $response = new Response();
  505. $middleware = new CsrfProtectionMiddleware();
  506. $middleware->skipCheckCallback(function (ServerRequestInterface $request) {
  507. $this->assertSame('POST', $request->getServerParams()['REQUEST_METHOD']);
  508. return true;
  509. });
  510. $handler = new TestRequestHandler(function ($request) {
  511. $this->assertEmpty($request->getParsedBody());
  512. return new Response();
  513. });
  514. $response = $middleware->process($request, $handler);
  515. $this->assertInstanceOf(Response::class, $response);
  516. }
  517. /**
  518. * Ensure salting is not consistent
  519. */
  520. public function testSaltToken(): void
  521. {
  522. $middleware = new CsrfProtectionMiddleware();
  523. $token = $middleware->createToken();
  524. $results = [];
  525. for ($i = 0; $i < 10; $i++) {
  526. $results[] = $middleware->saltToken($token);
  527. }
  528. $this->assertCount(10, array_unique($results));
  529. }
  530. }