CsrfProtectionMiddlewareTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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\Middleware\CsrfProtectionMiddleware;
  18. use Cake\Http\Response;
  19. use Cake\Http\ServerRequest;
  20. use Cake\TestSuite\TestCase;
  21. use Psr\Http\Message\ServerRequestInterface;
  22. use TestApp\Http\TestRequestHandler;
  23. use Zend\Diactoros\Response as DiactorosResponse;
  24. use Zend\Diactoros\Response\RedirectResponse;
  25. /**
  26. * Test for CsrfProtection
  27. */
  28. class CsrfProtectionMiddlewareTest extends TestCase
  29. {
  30. /**
  31. * Data provider for HTTP method tests.
  32. *
  33. * HEAD and GET do not populate $_POST or request->data.
  34. *
  35. * @return array
  36. */
  37. public static function safeHttpMethodProvider()
  38. {
  39. return [
  40. ['GET'],
  41. ['HEAD'],
  42. ];
  43. }
  44. /**
  45. * Data provider for HTTP methods that can contain request bodies.
  46. *
  47. * @return array
  48. */
  49. public static function httpMethodProvider()
  50. {
  51. return [
  52. ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD'],
  53. ];
  54. }
  55. /**
  56. * Provides the request handler
  57. *
  58. * @return \Psr\Http\Server\RequestHandlerInterface
  59. */
  60. protected function _getRequestHandler()
  61. {
  62. return new TestRequestHandler(function () {
  63. return new Response();
  64. });
  65. }
  66. /**
  67. * Test setting the cookie value
  68. *
  69. * @return void
  70. */
  71. public function testSettingCookie()
  72. {
  73. $request = new ServerRequest([
  74. 'environment' => ['REQUEST_METHOD' => 'GET'],
  75. 'webroot' => '/dir/',
  76. ]);
  77. $updatedRequest = null;
  78. $handler = new TestRequestHandler(function ($request) use (&$updatedRequest) {
  79. $updatedRequest = $request;
  80. return new Response();
  81. });
  82. $middleware = new CsrfProtectionMiddleware();
  83. $response = $middleware->process($request, $handler);
  84. $cookie = $response->getCookie('csrfToken');
  85. $this->assertNotEmpty($cookie, 'Should set a token.');
  86. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  87. $this->assertSame(0, $cookie['expires'], 'session duration.');
  88. $this->assertSame('/dir/', $cookie['path'], 'session path.');
  89. $this->assertEquals($cookie['value'], $updatedRequest->getAttribute('csrfToken'));
  90. }
  91. /**
  92. * Test that the CSRF tokens are not required for idempotent operations
  93. *
  94. * @dataProvider safeHttpMethodProvider
  95. * @return void
  96. */
  97. public function testSafeMethodNoCsrfRequired($method)
  98. {
  99. $request = new ServerRequest([
  100. 'environment' => [
  101. 'REQUEST_METHOD' => $method,
  102. 'HTTP_X_CSRF_TOKEN' => 'nope',
  103. ],
  104. 'cookies' => ['csrfToken' => 'testing123'],
  105. ]);
  106. // No exception means the test is valid
  107. $middleware = new CsrfProtectionMiddleware();
  108. $response = $middleware->process($request, $this->_getRequestHandler());
  109. $this->assertInstanceOf(Response::class, $response);
  110. }
  111. /**
  112. * Test that the CSRF tokens are set for redirect responses
  113. *
  114. * @return void
  115. */
  116. public function testRedirectResponseCookies()
  117. {
  118. $request = new ServerRequest([
  119. 'environment' => ['REQUEST_METHOD' => 'GET'],
  120. ]);
  121. $handler = new TestRequestHandler(function () {
  122. return new RedirectResponse('/');
  123. });
  124. $middleware = new CsrfProtectionMiddleware();
  125. $response = $middleware->process($request, $handler);
  126. $this->assertStringContainsString('csrfToken=', $response->getHeaderLine('Set-Cookie'));
  127. }
  128. /**
  129. * Test that the CSRF tokens are set for diactoros responses
  130. *
  131. * @return void
  132. */
  133. public function testDiactorosResponseCookies()
  134. {
  135. $request = new ServerRequest([
  136. 'environment' => ['REQUEST_METHOD' => 'GET'],
  137. ]);
  138. $handler = new TestRequestHandler(function () {
  139. return new DiactorosResponse();
  140. });
  141. $middleware = new CsrfProtectionMiddleware();
  142. $response = $middleware->process($request, $handler);
  143. $this->assertStringContainsString('csrfToken=', $response->getHeaderLine('Set-Cookie'));
  144. }
  145. /**
  146. * Test that the X-CSRF-Token works with the various http methods.
  147. *
  148. * @dataProvider httpMethodProvider
  149. * @return void
  150. */
  151. public function testValidTokenInHeader($method)
  152. {
  153. $request = new ServerRequest([
  154. 'environment' => [
  155. 'REQUEST_METHOD' => $method,
  156. 'HTTP_X_CSRF_TOKEN' => 'testing123',
  157. ],
  158. 'post' => ['a' => 'b'],
  159. 'cookies' => ['csrfToken' => 'testing123'],
  160. ]);
  161. $response = new Response();
  162. // No exception means the test is valid
  163. $middleware = new CsrfProtectionMiddleware();
  164. $response = $middleware->process($request, $this->_getRequestHandler());
  165. $this->assertInstanceOf(Response::class, $response);
  166. }
  167. /**
  168. * Test that the X-CSRF-Token works with the various http methods.
  169. *
  170. * @dataProvider httpMethodProvider
  171. * @return void
  172. */
  173. public function testInvalidTokenInHeader($method)
  174. {
  175. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  176. $request = new ServerRequest([
  177. 'environment' => [
  178. 'REQUEST_METHOD' => $method,
  179. 'HTTP_X_CSRF_TOKEN' => 'nope',
  180. ],
  181. 'post' => ['a' => 'b'],
  182. 'cookies' => ['csrfToken' => 'testing123'],
  183. ]);
  184. $middleware = new CsrfProtectionMiddleware();
  185. $middleware->process($request, $this->_getRequestHandler());
  186. }
  187. /**
  188. * Test that request data works with the various http methods.
  189. *
  190. * @dataProvider httpMethodProvider
  191. * @return void
  192. */
  193. public function testValidTokenRequestData($method)
  194. {
  195. $request = new ServerRequest([
  196. 'environment' => [
  197. 'REQUEST_METHOD' => $method,
  198. ],
  199. 'post' => ['_csrfToken' => 'testing123'],
  200. 'cookies' => ['csrfToken' => 'testing123'],
  201. ]);
  202. $handler = new TestRequestHandler(function ($request) {
  203. $this->assertNull($request->getData('_csrfToken'));
  204. return new Response();
  205. });
  206. // No exception means everything is OK
  207. $middleware = new CsrfProtectionMiddleware();
  208. $middleware->process($request, $handler);
  209. }
  210. /**
  211. * Test that request data works with the various http methods.
  212. *
  213. * @dataProvider httpMethodProvider
  214. * @return void
  215. */
  216. public function testInvalidTokenRequestData($method)
  217. {
  218. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  219. $request = new ServerRequest([
  220. 'environment' => [
  221. 'REQUEST_METHOD' => $method,
  222. ],
  223. 'post' => ['_csrfToken' => 'nope'],
  224. 'cookies' => ['csrfToken' => 'testing123'],
  225. ]);
  226. $middleware = new CsrfProtectionMiddleware();
  227. $middleware->process($request, $this->_getRequestHandler());
  228. }
  229. /**
  230. * Test that missing post field fails
  231. *
  232. * @return void
  233. */
  234. public function testInvalidTokenRequestDataMissing()
  235. {
  236. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  237. $request = new ServerRequest([
  238. 'environment' => [
  239. 'REQUEST_METHOD' => 'POST',
  240. ],
  241. 'post' => [],
  242. 'cookies' => ['csrfToken' => 'testing123'],
  243. ]);
  244. $middleware = new CsrfProtectionMiddleware();
  245. $middleware->process($request, $this->_getRequestHandler());
  246. }
  247. /**
  248. * Test that missing header and cookie fails
  249. *
  250. * @dataProvider httpMethodProvider
  251. * @return void
  252. */
  253. public function testInvalidTokenMissingCookie($method)
  254. {
  255. $this->expectException(\Cake\Http\Exception\InvalidCsrfTokenException::class);
  256. $request = new ServerRequest([
  257. 'environment' => [
  258. 'REQUEST_METHOD' => $method,
  259. ],
  260. 'post' => ['_csrfToken' => 'could-be-valid'],
  261. 'cookies' => [],
  262. ]);
  263. $middleware = new CsrfProtectionMiddleware();
  264. $middleware->process($request, $this->_getRequestHandler());
  265. }
  266. /**
  267. * Test that the configuration options work.
  268. *
  269. * @return void
  270. */
  271. public function testConfigurationCookieCreate()
  272. {
  273. $request = new ServerRequest([
  274. 'environment' => ['REQUEST_METHOD' => 'GET'],
  275. 'webroot' => '/dir/',
  276. ]);
  277. $middleware = new CsrfProtectionMiddleware([
  278. 'cookieName' => 'token',
  279. 'expiry' => '+1 hour',
  280. 'secure' => true,
  281. 'httpOnly' => true,
  282. ]);
  283. $response = $middleware->process($request, $this->_getRequestHandler());
  284. $this->assertEmpty($response->getCookie('csrfToken'));
  285. $cookie = $response->getCookie('token');
  286. $this->assertNotEmpty($cookie, 'Should set a token.');
  287. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  288. $this->assertWithinRange(strtotime('+1 hour'), $cookie['expires'], 1, 'session duration.');
  289. $this->assertSame('/dir/', $cookie['path'], 'session path.');
  290. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  291. $this->assertTrue($cookie['httponly'], 'cookie httpOnly flag missing');
  292. }
  293. /**
  294. * Test that the configuration options work.
  295. *
  296. * There should be no exception thrown.
  297. *
  298. * @return void
  299. */
  300. public function testConfigurationValidate()
  301. {
  302. $request = new ServerRequest([
  303. 'environment' => ['REQUEST_METHOD' => 'POST'],
  304. 'cookies' => ['csrfToken' => 'nope', 'token' => 'yes'],
  305. 'post' => ['_csrfToken' => 'no match', 'token' => 'yes'],
  306. ]);
  307. $response = new Response();
  308. $middleware = new CsrfProtectionMiddleware([
  309. 'cookieName' => 'token',
  310. 'field' => 'token',
  311. 'expiry' => 90,
  312. ]);
  313. $response = $middleware->process($request, $this->_getRequestHandler());
  314. $this->assertInstanceOf(Response::class, $response);
  315. }
  316. /**
  317. * @return void
  318. */
  319. public function testSkippingTokenCheckUsingWhitelistCallback()
  320. {
  321. $request = new ServerRequest([
  322. 'post' => [
  323. '_csrfToken' => 'foo',
  324. ],
  325. 'environment' => [
  326. 'REQUEST_METHOD' => 'POST',
  327. ],
  328. ]);
  329. $response = new Response();
  330. $middleware = new CsrfProtectionMiddleware();
  331. $middleware->whitelistCallback(function (ServerRequestInterface $request) {
  332. $this->assertSame('POST', $request->getServerParams()['REQUEST_METHOD']);
  333. return true;
  334. });
  335. $handler = new TestRequestHandler(function ($request) {
  336. $this->assertEmpty($request->getParsedBody());
  337. return new Response();
  338. });
  339. $response = $middleware->process($request, $handler);
  340. $this->assertInstanceOf(Response::class, $response);
  341. }
  342. }