CsrfProtectionMiddlewareTest.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 empty value cookies are rejected
  350. *
  351. * @return void
  352. */
  353. public function testInvalidTokenEmptyStringCookies()
  354. {
  355. $this->expectException(InvalidCsrfTokenException::class);
  356. $request = new ServerRequest([
  357. 'environment' => [
  358. 'REQUEST_METHOD' => 'POST',
  359. ],
  360. 'post' => ['_csrfToken' => '*(&'],
  361. // Invalid data that can't be base64 decoded.
  362. 'cookies' => ['csrfToken' => '*(&'],
  363. ]);
  364. $middleware = new CsrfProtectionMiddleware();
  365. $middleware->process($request, $this->_getRequestHandler());
  366. }
  367. /**
  368. * Test that request non string cookies are ignored.
  369. */
  370. public function testInvalidTokenNonStringCookies(): void
  371. {
  372. $this->expectException(InvalidCsrfTokenException::class);
  373. $request = new ServerRequest([
  374. 'environment' => [
  375. 'REQUEST_METHOD' => 'POST',
  376. ],
  377. 'post' => ['_csrfToken' => ['nope']],
  378. 'cookies' => ['csrfToken' => ['nope']],
  379. ]);
  380. $middleware = new CsrfProtectionMiddleware();
  381. $middleware->process($request, $this->_getRequestHandler());
  382. }
  383. /**
  384. * Test that request data works with the various http methods.
  385. *
  386. * @dataProvider httpMethodProvider
  387. */
  388. public function testInvalidTokenRequestData(string $method): void
  389. {
  390. $request = new ServerRequest([
  391. 'environment' => [
  392. 'REQUEST_METHOD' => $method,
  393. ],
  394. 'post' => ['_csrfToken' => 'nope'],
  395. 'cookies' => ['csrfToken' => 'testing123'],
  396. ]);
  397. $middleware = new CsrfProtectionMiddleware();
  398. try {
  399. $middleware->process($request, $this->_getRequestHandler());
  400. $this->fail();
  401. } catch (InvalidCsrfTokenException $exception) {
  402. $responseHeaders = $exception->getHeaders();
  403. $this->assertArrayHasKey('Set-Cookie', $responseHeaders);
  404. $cookie = Cookie::createFromHeaderString($responseHeaders['Set-Cookie']);
  405. $this->assertSame('csrfToken', $cookie->getName(), 'Should automatically delete cookie with invalid CSRF token');
  406. $this->assertTrue($cookie->isExpired(), 'Should automatically delete cookie with invalid CSRF token');
  407. }
  408. }
  409. /**
  410. * Test that tokens cannot be simple matches and must pass our hmac.
  411. */
  412. public function testInvalidTokenIncorrectOrigin(): void
  413. {
  414. $request = new ServerRequest([
  415. 'environment' => [
  416. 'REQUEST_METHOD' => 'POST',
  417. ],
  418. 'post' => ['_csrfToken' => 'this is a match'],
  419. 'cookies' => ['csrfToken' => 'this is a match'],
  420. ]);
  421. $middleware = new CsrfProtectionMiddleware();
  422. $this->expectException(InvalidCsrfTokenException::class);
  423. $middleware->process($request, $this->_getRequestHandler());
  424. }
  425. /**
  426. * Test that missing post field fails
  427. */
  428. public function testInvalidTokenRequestDataMissing(): void
  429. {
  430. $request = new ServerRequest([
  431. 'environment' => [
  432. 'REQUEST_METHOD' => 'POST',
  433. ],
  434. 'post' => [],
  435. 'cookies' => ['csrfToken' => 'testing123'],
  436. ]);
  437. $middleware = new CsrfProtectionMiddleware();
  438. $this->expectException(InvalidCsrfTokenException::class);
  439. $middleware->process($request, $this->_getRequestHandler());
  440. }
  441. /**
  442. * Test that missing header and cookie fails
  443. *
  444. * @dataProvider httpMethodProvider
  445. */
  446. public function testInvalidTokenMissingCookie(string $method): void
  447. {
  448. $request = new ServerRequest([
  449. 'environment' => [
  450. 'REQUEST_METHOD' => $method,
  451. ],
  452. 'post' => ['_csrfToken' => 'could-be-valid'],
  453. 'cookies' => [],
  454. ]);
  455. $middleware = new CsrfProtectionMiddleware();
  456. try {
  457. $middleware->process($request, $this->_getRequestHandler());
  458. $this->fail();
  459. } catch (InvalidCsrfTokenException $exception) {
  460. $responseHeaders = $exception->getHeaders();
  461. $this->assertEmpty($responseHeaders, 'Should not send any header');
  462. }
  463. }
  464. /**
  465. * Test that the configuration options work.
  466. */
  467. public function testConfigurationCookieCreate(): void
  468. {
  469. $request = new ServerRequest([
  470. 'environment' => ['REQUEST_METHOD' => 'GET'],
  471. 'webroot' => '/dir/',
  472. ]);
  473. $middleware = new CsrfProtectionMiddleware([
  474. 'cookieName' => 'token',
  475. 'expiry' => '+1 hour',
  476. 'secure' => true,
  477. 'httponly' => true,
  478. 'samesite' => CookieInterface::SAMESITE_STRICT,
  479. ]);
  480. $response = $middleware->process($request, $this->_getRequestHandler());
  481. $this->assertEmpty($response->getCookie('csrfToken'));
  482. $cookie = $response->getCookie('token');
  483. $this->assertNotEmpty($cookie, 'Should set a token.');
  484. $this->assertMatchesRegularExpression('/^[a-z0-9\/+]+={0,2}$/i', $cookie['value'], 'Should look like base64.');
  485. $this->assertWithinRange(strtotime('+1 hour'), $cookie['expires'], 1, 'session duration.');
  486. $this->assertSame('/dir/', $cookie['path'], 'session path.');
  487. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  488. $this->assertTrue($cookie['httponly'], 'cookie httponly flag missing');
  489. $this->assertSame(CookieInterface::SAMESITE_STRICT, $cookie['samesite'], 'samesite attribute missing');
  490. }
  491. /**
  492. * Test that the configuration options work.
  493. *
  494. * There should be no exception thrown.
  495. */
  496. public function testConfigurationValidate(): void
  497. {
  498. $middleware = new CsrfProtectionMiddleware([
  499. 'cookieName' => 'token',
  500. 'field' => 'token',
  501. 'expiry' => 90,
  502. ]);
  503. $token = $middleware->createToken();
  504. $request = new ServerRequest([
  505. 'environment' => ['REQUEST_METHOD' => 'POST'],
  506. 'cookies' => ['csrfToken' => 'nope', 'token' => $token],
  507. 'post' => ['_csrfToken' => 'no match', 'token' => $token],
  508. ]);
  509. $response = new Response();
  510. $response = $middleware->process($request, $this->_getRequestHandler());
  511. $this->assertInstanceOf(Response::class, $response);
  512. }
  513. public function testSkippingTokenCheckUsingSkipCheckCallback(): void
  514. {
  515. $request = new ServerRequest([
  516. 'post' => [
  517. '_csrfToken' => 'foo',
  518. ],
  519. 'environment' => [
  520. 'REQUEST_METHOD' => 'POST',
  521. ],
  522. ]);
  523. $response = new Response();
  524. $middleware = new CsrfProtectionMiddleware();
  525. $middleware->skipCheckCallback(function (ServerRequestInterface $request) {
  526. $this->assertSame('POST', $request->getServerParams()['REQUEST_METHOD']);
  527. return true;
  528. });
  529. $handler = new TestRequestHandler(function ($request) {
  530. $this->assertEmpty($request->getParsedBody());
  531. return new Response();
  532. });
  533. $response = $middleware->process($request, $handler);
  534. $this->assertInstanceOf(Response::class, $response);
  535. }
  536. /**
  537. * Ensure salting is not consistent
  538. */
  539. public function testSaltToken(): void
  540. {
  541. $middleware = new CsrfProtectionMiddleware();
  542. $token = $middleware->createToken();
  543. $results = [];
  544. for ($i = 0; $i < 10; $i++) {
  545. $results[] = $middleware->saltToken($token);
  546. }
  547. $this->assertCount(10, array_unique($results));
  548. }
  549. }