CsrfProtectionMiddlewareTest.php 12 KB

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