CsrfProtectionMiddlewareTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.5.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Http\Middleware;
  16. use Cake\Http\Middleware\CsrfProtectionMiddleware;
  17. use Cake\Http\Response;
  18. use Cake\Http\ServerRequest;
  19. use Cake\I18n\Time;
  20. use Cake\TestSuite\TestCase;
  21. use Laminas\Diactoros\Response as DiactorosResponse;
  22. use Laminas\Diactoros\Response\RedirectResponse;
  23. use Psr\Http\Message\ServerRequestInterface;
  24. /**
  25. * Test for CsrfProtection
  26. */
  27. class CsrfProtectionMiddlewareTest extends TestCase
  28. {
  29. /**
  30. * Data provider for HTTP method tests.
  31. *
  32. * HEAD and GET do not populate $_POST or request->data.
  33. *
  34. * @return array
  35. */
  36. public static function safeHttpMethodProvider()
  37. {
  38. return [
  39. ['GET'],
  40. ['HEAD'],
  41. ];
  42. }
  43. /**
  44. * Data provider for HTTP methods that can contain request bodies.
  45. *
  46. * @return array
  47. */
  48. public static function httpMethodProvider()
  49. {
  50. return [
  51. ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD'],
  52. ];
  53. }
  54. /**
  55. * Provides the callback for the next middleware
  56. *
  57. * @return callable
  58. */
  59. protected function _getNextClosure()
  60. {
  61. return function ($request, $response) {
  62. return $response;
  63. };
  64. }
  65. /**
  66. * Test setting the cookie value
  67. *
  68. * @return void
  69. */
  70. public function testSettingCookie()
  71. {
  72. $request = new ServerRequest([
  73. 'environment' => ['REQUEST_METHOD' => 'GET'],
  74. 'webroot' => '/dir/',
  75. ]);
  76. $response = new Response();
  77. $closure = function ($request, $response) {
  78. $cookie = $response->getCookie('csrfToken');
  79. $this->assertNotEmpty($cookie, 'Should set a token.');
  80. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  81. $this->assertEquals(0, $cookie['expire'], 'session duration.');
  82. $this->assertEquals('/dir/', $cookie['path'], 'session path.');
  83. $this->assertEquals($cookie['value'], $request->getParam('_csrfToken'));
  84. $this->assertRegExp('/^[a-z0-9]+$/', $cookie['value']);
  85. };
  86. $middleware = new CsrfProtectionMiddleware();
  87. $middleware($request, $response, $closure);
  88. }
  89. /**
  90. * Test that the CSRF tokens are not required for idempotent operations
  91. *
  92. * @dataProvider safeHttpMethodProvider
  93. * @return void
  94. */
  95. public function testSafeMethodNoCsrfRequired($method)
  96. {
  97. $request = new ServerRequest([
  98. 'environment' => [
  99. 'REQUEST_METHOD' => $method,
  100. 'HTTP_X_CSRF_TOKEN' => 'nope',
  101. ],
  102. 'cookies' => ['csrfToken' => 'testing123'],
  103. ]);
  104. $response = new Response();
  105. // No exception means the test is valid
  106. $middleware = new CsrfProtectionMiddleware();
  107. $response = $middleware($request, $response, $this->_getNextClosure());
  108. $this->assertInstanceOf(Response::class, $response);
  109. }
  110. /**
  111. * Test that the X-CSRF-Token works with the various http methods.
  112. *
  113. * @dataProvider httpMethodProvider
  114. * @return void
  115. */
  116. public function testValidTokenInHeader($method)
  117. {
  118. $request = new ServerRequest([
  119. 'environment' => [
  120. 'REQUEST_METHOD' => $method,
  121. 'HTTP_X_CSRF_TOKEN' => 'testing123',
  122. ],
  123. 'post' => ['a' => 'b'],
  124. 'cookies' => ['csrfToken' => 'testing123'],
  125. ]);
  126. $response = new Response();
  127. // No exception means the test is valid
  128. $middleware = new CsrfProtectionMiddleware();
  129. $response = $middleware($request, $response, $this->_getNextClosure());
  130. $this->assertInstanceOf(Response::class, $response);
  131. }
  132. /**
  133. * Test that the X-CSRF-Token works with the various http methods.
  134. *
  135. * @dataProvider httpMethodProvider
  136. * @return void
  137. */
  138. public function testInvalidTokenInHeader($method)
  139. {
  140. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  141. $request = new ServerRequest([
  142. 'environment' => [
  143. 'REQUEST_METHOD' => $method,
  144. 'HTTP_X_CSRF_TOKEN' => 'nope',
  145. ],
  146. 'post' => ['a' => 'b'],
  147. 'cookies' => ['csrfToken' => 'testing123'],
  148. ]);
  149. $response = new Response();
  150. $middleware = new CsrfProtectionMiddleware();
  151. $middleware($request, $response, $this->_getNextClosure());
  152. }
  153. /**
  154. * Test that request data works with the various http methods.
  155. *
  156. * @dataProvider httpMethodProvider
  157. * @return void
  158. */
  159. public function testValidTokenRequestData($method)
  160. {
  161. $request = new ServerRequest([
  162. 'environment' => [
  163. 'REQUEST_METHOD' => $method,
  164. ],
  165. 'post' => ['_csrfToken' => 'testing123'],
  166. 'cookies' => ['csrfToken' => 'testing123'],
  167. ]);
  168. $response = new Response();
  169. $closure = function ($request, $response) {
  170. $this->assertNull($request->getData('_csrfToken'));
  171. };
  172. // No exception means everything is OK
  173. $middleware = new CsrfProtectionMiddleware();
  174. $middleware($request, $response, $closure);
  175. }
  176. /**
  177. * Test that the X-CSRF-Token works with the various http methods.
  178. *
  179. * @dataProvider httpMethodProvider
  180. * @return void
  181. */
  182. public function testValidTokenInHeaderVerifySource($method)
  183. {
  184. $middleware = new CsrfProtectionMiddleware(['verifyTokenSource' => true]);
  185. $token = $middleware->createToken();
  186. $this->assertRegexp('/^[a-z0-9]+$/', $token, 'Token should not have unencoded binary data.');
  187. $request = new ServerRequest([
  188. 'environment' => [
  189. 'REQUEST_METHOD' => $method,
  190. 'HTTP_X_CSRF_TOKEN' => $token,
  191. ],
  192. 'post' => ['a' => 'b'],
  193. 'cookies' => ['csrfToken' => $token],
  194. ]);
  195. $response = new Response();
  196. // No exception means the test is valid
  197. $response = $middleware($request, $response, $this->_getNextClosure());
  198. $this->assertInstanceOf(Response::class, $response);
  199. }
  200. /**
  201. * Test that the X-CSRF-Token works with the various http methods.
  202. *
  203. * @dataProvider httpMethodProvider
  204. * @return void
  205. */
  206. public function testInvalidTokenInHeaderVerifySource($method)
  207. {
  208. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  209. $request = new ServerRequest([
  210. 'environment' => [
  211. 'REQUEST_METHOD' => $method,
  212. // Even though the values match they are not signed.
  213. 'HTTP_X_CSRF_TOKEN' => 'nope',
  214. ],
  215. 'post' => ['a' => 'b'],
  216. 'cookies' => ['csrfToken' => 'nope'],
  217. ]);
  218. $response = new Response();
  219. $middleware = new CsrfProtectionMiddleware(['verifyTokenSource' => true]);
  220. $middleware($request, $response, $this->_getNextClosure());
  221. }
  222. /**
  223. * Test that request data works with the various http methods.
  224. *
  225. * @dataProvider httpMethodProvider
  226. * @return void
  227. */
  228. public function testValidTokenRequestDataVerifySource($method)
  229. {
  230. $middleware = new CsrfProtectionMiddleware(['verifyTokenSource' => true]);
  231. $token = $middleware->createToken();
  232. $request = new ServerRequest([
  233. 'environment' => [
  234. 'REQUEST_METHOD' => $method,
  235. ],
  236. 'post' => ['_csrfToken' => $token],
  237. 'cookies' => ['csrfToken' => $token],
  238. ]);
  239. $response = new Response();
  240. $closure = function ($request, $response) {
  241. $this->assertNull($request->getData('_csrfToken'));
  242. };
  243. // No exception means everything is OK
  244. $middleware($request, $response, $closure);
  245. }
  246. /**
  247. * Test that request data works with the various http methods.
  248. *
  249. * @dataProvider httpMethodProvider
  250. * @return void
  251. */
  252. public function testInvalidTokenRequestDataVerifySource($method)
  253. {
  254. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  255. $request = new ServerRequest([
  256. 'environment' => [
  257. 'REQUEST_METHOD' => $method,
  258. ],
  259. // Even though the tokens match they are not signed.
  260. 'post' => ['_csrfToken' => 'example-token'],
  261. 'cookies' => ['csrfToken' => 'example-token'],
  262. ]);
  263. $response = new Response();
  264. $middleware = new CsrfProtectionMiddleware(['verifyTokenSource' => true]);
  265. $middleware($request, $response, $this->_getNextClosure());
  266. }
  267. /**
  268. * Test that request data works with the various http methods.
  269. *
  270. * @dataProvider httpMethodProvider
  271. * @return void
  272. */
  273. public function testInvalidTokenRequestData($method)
  274. {
  275. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  276. $request = new ServerRequest([
  277. 'environment' => [
  278. 'REQUEST_METHOD' => $method,
  279. ],
  280. 'post' => ['_csrfToken' => 'nope'],
  281. 'cookies' => ['csrfToken' => 'testing123'],
  282. ]);
  283. $response = new Response();
  284. $middleware = new CsrfProtectionMiddleware();
  285. $middleware($request, $response, $this->_getNextClosure());
  286. }
  287. /**
  288. * Test that missing post field fails
  289. *
  290. * @return void
  291. */
  292. public function testInvalidTokenRequestDataMissing()
  293. {
  294. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  295. $request = new ServerRequest([
  296. 'environment' => [
  297. 'REQUEST_METHOD' => 'POST',
  298. ],
  299. 'post' => [],
  300. 'cookies' => ['csrfToken' => 'testing123'],
  301. ]);
  302. $response = new Response();
  303. $middleware = new CsrfProtectionMiddleware();
  304. $middleware($request, $response, $this->_getNextClosure());
  305. }
  306. /**
  307. * Test that request data works with the various http methods.
  308. *
  309. * @return void
  310. */
  311. public function testInvalidTokenNonStringData()
  312. {
  313. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  314. $request = new ServerRequest([
  315. 'environment' => [
  316. 'REQUEST_METHOD' => 'POST',
  317. ],
  318. 'post' => ['_csrfToken' => ['nope']],
  319. 'cookies' => ['csrfToken' => ['nope']],
  320. ]);
  321. $response = new Response();
  322. $middleware = new CsrfProtectionMiddleware();
  323. $middleware($request, $response, $this->_getNextClosure());
  324. }
  325. /**
  326. * Test that missing header and cookie fails
  327. *
  328. * @dataProvider httpMethodProvider
  329. * @return void
  330. */
  331. public function testInvalidTokenMissingCookie($method)
  332. {
  333. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  334. $request = new ServerRequest([
  335. 'environment' => [
  336. 'REQUEST_METHOD' => $method,
  337. ],
  338. 'post' => ['_csrfToken' => 'could-be-valid'],
  339. 'cookies' => [],
  340. ]);
  341. $response = new Response();
  342. $middleware = new CsrfProtectionMiddleware();
  343. $middleware($request, $response, $this->_getNextClosure());
  344. }
  345. /**
  346. * Test that the configuration options work.
  347. *
  348. * @return void
  349. */
  350. public function testConfigurationCookieCreate()
  351. {
  352. $request = new ServerRequest([
  353. 'environment' => ['REQUEST_METHOD' => 'GET'],
  354. 'webroot' => '/dir/',
  355. ]);
  356. $response = new Response();
  357. $closure = function ($request, $response) {
  358. $this->assertEmpty($response->getCookie('csrfToken'));
  359. $cookie = $response->getCookie('token');
  360. $this->assertNotEmpty($cookie, 'Should set a token.');
  361. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  362. $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');
  363. $this->assertEquals('/dir/', $cookie['path'], 'session path.');
  364. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  365. $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');
  366. };
  367. $middleware = new CsrfProtectionMiddleware([
  368. 'cookieName' => 'token',
  369. 'expiry' => '+1 hour',
  370. 'secure' => true,
  371. 'httpOnly' => true,
  372. ]);
  373. $middleware($request, $response, $closure);
  374. }
  375. /**
  376. * Test that the configuration options work.
  377. *
  378. * There should be no exception thrown.
  379. *
  380. * @return void
  381. */
  382. public function testConfigurationValidate()
  383. {
  384. $request = new ServerRequest([
  385. 'environment' => ['REQUEST_METHOD' => 'POST'],
  386. 'cookies' => ['csrfToken' => 'nope', 'token' => 'yes'],
  387. 'post' => ['_csrfToken' => 'no match', 'token' => 'yes'],
  388. ]);
  389. $response = new Response();
  390. $middleware = new CsrfProtectionMiddleware([
  391. 'cookieName' => 'token',
  392. 'field' => 'token',
  393. 'expiry' => 90,
  394. ]);
  395. $response = $middleware($request, $response, $this->_getNextClosure());
  396. $this->assertInstanceOf(Response::class, $response);
  397. }
  398. /**
  399. * @return void
  400. */
  401. public function testSkippingTokenCheckUsingWhitelistCallback()
  402. {
  403. $request = new ServerRequest([
  404. 'environment' => [
  405. 'REQUEST_METHOD' => 'POST',
  406. ],
  407. ]);
  408. $response = new Response();
  409. $middleware = new CsrfProtectionMiddleware();
  410. $middleware->whitelistCallback(function (ServerRequestInterface $request) {
  411. $this->assertSame('POST', $request->getServerParams()['REQUEST_METHOD']);
  412. return true;
  413. });
  414. $response = $middleware($request, $response, $this->_getNextClosure());
  415. $this->assertInstanceOf(Response::class, $response);
  416. }
  417. /**
  418. * Test the situation where the app is upgraded from 3.9.2 or earlier to 3.9.3 or later,
  419. * without deleting route cache.
  420. *
  421. * @return void
  422. */
  423. public function testMissingSamesite()
  424. {
  425. $request = new ServerRequest([
  426. 'environment' => ['REQUEST_METHOD' => 'GET'],
  427. 'webroot' => '/dir/',
  428. ]);
  429. $response = new Response();
  430. $closure = function ($request, $response) {
  431. };
  432. $middleware = new CsrfProtectionMiddleware();
  433. // simulate 3.9.2 or earlier by deleting "samesite" config
  434. $reflection = new \ReflectionClass($middleware);
  435. $property = $reflection->getProperty('_config');
  436. $property->setAccessible(true);
  437. $defaultConfig = $property->getValue($middleware);
  438. unset($defaultConfig['samesite']);
  439. $property->setValue($middleware, $defaultConfig);
  440. $middleware($request, $response, $closure);
  441. $this->assertTrue(true);
  442. }
  443. }