CsrfComponentTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller\Component;
  16. use Cake\Controller\ComponentRegistry;
  17. use Cake\Controller\Component\CsrfComponent;
  18. use Cake\Event\Event;
  19. use Cake\I18n\Time;
  20. use Cake\Network\Request;
  21. use Cake\Network\Response;
  22. use Cake\TestSuite\TestCase;
  23. /**
  24. * CsrfComponent test.
  25. */
  26. class CsrfComponentTest extends TestCase
  27. {
  28. /**
  29. * setup
  30. *
  31. * @return void
  32. */
  33. public function setUp()
  34. {
  35. parent::setUp();
  36. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  37. $this->registry = new ComponentRegistry($controller);
  38. $this->component = new CsrfComponent($this->registry);
  39. }
  40. /**
  41. * teardown
  42. *
  43. * @return void
  44. */
  45. public function tearDown()
  46. {
  47. parent::tearDown();
  48. unset($this->component);
  49. }
  50. /**
  51. * Test setting the cookie value
  52. *
  53. * @return void
  54. * @triggers Controller.startup $controller
  55. */
  56. public function testSettingCookie()
  57. {
  58. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  59. $controller->request = new Request([
  60. 'environment' => ['REQUEST_METHOD' => 'GET'],
  61. 'webroot' => '/dir/',
  62. ]);
  63. $controller->response = new Response();
  64. $event = new Event('Controller.startup', $controller);
  65. $this->component->startup($event);
  66. $cookie = $controller->response->cookie('csrfToken');
  67. $this->assertNotEmpty($cookie, 'Should set a token.');
  68. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  69. $this->assertEquals(0, $cookie['expire'], 'session duration.');
  70. $this->assertEquals('/dir/', $cookie['path'], 'session path.');
  71. $this->assertEquals($cookie['value'], $controller->request->params['_csrfToken']);
  72. }
  73. /**
  74. * Data provider for HTTP method tests.
  75. *
  76. * @return void
  77. */
  78. public static function safeHttpMethodProvider()
  79. {
  80. return [
  81. ['GET'], ['OPTIONS'], ['HEAD']
  82. ];
  83. }
  84. /**
  85. * Test that the CSRF tokens are not required for idempotent operations
  86. *
  87. * @dataProvider safeHttpMethodProvider
  88. * @return void
  89. */
  90. public function testSafeMethodNoCsrfRequired($method)
  91. {
  92. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  93. $controller->request = new Request([
  94. 'environment' => [
  95. 'REQUEST_METHOD' => $method,
  96. 'HTTP_X_CSRF_TOKEN' => 'nope',
  97. ],
  98. 'cookies' => ['csrfToken' => 'testing123']
  99. ]);
  100. $controller->response = new Response();
  101. $event = new Event('Controller.startup', $controller);
  102. $result = $this->component->startup($event);
  103. $this->assertNull($result, 'No exception means valid.');
  104. }
  105. /**
  106. * Data provider for HTTP method tests.
  107. *
  108. * @return void
  109. */
  110. public static function httpMethodProvider()
  111. {
  112. return [
  113. ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD']
  114. ];
  115. }
  116. /**
  117. * Test that the X-CSRF-Token works with the various http methods.
  118. *
  119. * @dataProvider httpMethodProvider
  120. * @return void
  121. * @triggers Controller.startup $controller
  122. */
  123. public function testValidTokenInHeader($method)
  124. {
  125. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  126. $controller->request = new Request([
  127. 'environment' => [
  128. 'REQUEST_METHOD' => $method,
  129. 'HTTP_X_CSRF_TOKEN' => 'testing123',
  130. ],
  131. 'cookies' => ['csrfToken' => 'testing123']
  132. ]);
  133. $controller->response = new Response();
  134. $event = new Event('Controller.startup', $controller);
  135. $result = $this->component->startup($event);
  136. $this->assertNull($result, 'No exception means valid.');
  137. }
  138. /**
  139. * Test that the X-CSRF-Token works with the various http methods.
  140. *
  141. * @dataProvider httpMethodProvider
  142. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  143. * @return void
  144. * @triggers Controller.startup $controller
  145. */
  146. public function testInvalidTokenInHeader($method)
  147. {
  148. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  149. $controller->request = new Request([
  150. 'environment' => [
  151. 'REQUEST_METHOD' => $method,
  152. 'HTTP_X_CSRF_TOKEN' => 'nope',
  153. ],
  154. 'cookies' => ['csrfToken' => 'testing123']
  155. ]);
  156. $controller->response = new Response();
  157. $event = new Event('Controller.startup', $controller);
  158. $this->component->startup($event);
  159. }
  160. /**
  161. * Test that request data works with the various http methods.
  162. *
  163. * @dataProvider httpMethodProvider
  164. * @return void
  165. * @triggers Controller.startup $controller
  166. */
  167. public function testValidTokenRequestData($method)
  168. {
  169. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  170. $controller->request = new Request([
  171. 'environment' => [
  172. 'REQUEST_METHOD' => $method,
  173. ],
  174. 'post' => ['_csrfToken' => 'testing123'],
  175. 'cookies' => ['csrfToken' => 'testing123']
  176. ]);
  177. $controller->response = new Response();
  178. $event = new Event('Controller.startup', $controller);
  179. $result = $this->component->startup($event);
  180. $this->assertNull($result, 'No exception means valid.');
  181. $this->assertFalse(isset($controller->request->data['_csrfToken']));
  182. }
  183. /**
  184. * Test that request data works with the various http methods.
  185. *
  186. * @dataProvider httpMethodProvider
  187. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  188. * @return void
  189. */
  190. public function testInvalidTokenRequestData($method)
  191. {
  192. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  193. $controller->request = new Request([
  194. 'environment' => [
  195. 'REQUEST_METHOD' => $method,
  196. ],
  197. 'post' => ['_csrfToken' => 'nope'],
  198. 'cookies' => ['csrfToken' => 'testing123']
  199. ]);
  200. $controller->response = new Response();
  201. $event = new Event('Controller.startup', $controller);
  202. $this->component->startup($event);
  203. }
  204. /**
  205. * Test that missing post field fails
  206. *
  207. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  208. * @return void
  209. */
  210. public function testInvalidTokenRequestDataMissing()
  211. {
  212. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  213. $controller->request = new Request([
  214. 'environment' => [
  215. 'REQUEST_METHOD' => 'POST',
  216. ],
  217. 'post' => [],
  218. 'cookies' => ['csrfToken' => 'testing123']
  219. ]);
  220. $controller->response = new Response();
  221. $event = new Event('Controller.startup', $controller);
  222. $this->component->startup($event);
  223. }
  224. /**
  225. * Test that missing header and cookie fails
  226. *
  227. * @dataProvider httpMethodProvider
  228. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  229. * @return void
  230. */
  231. public function testInvalidTokenMissingCookie($method)
  232. {
  233. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  234. $controller->request = new Request([
  235. 'environment' => [
  236. 'REQUEST_METHOD' => $method
  237. ],
  238. 'post' => ['_csrfToken' => 'could-be-valid'],
  239. 'cookies' => []
  240. ]);
  241. $controller->response = new Response();
  242. $event = new Event('Controller.startup', $controller);
  243. $this->component->startup($event);
  244. }
  245. /**
  246. * Test that CSRF checks are not applied to request action requests.
  247. *
  248. * @return void
  249. * @triggers Controller.startup $controller
  250. */
  251. public function testCsrfValidationSkipsRequestAction()
  252. {
  253. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  254. $controller->request = new Request([
  255. 'environment' => ['REQUEST_METHOD' => 'POST'],
  256. 'params' => ['requested' => 1],
  257. 'post' => ['_csrfToken' => 'nope'],
  258. 'cookies' => ['csrfToken' => 'testing123']
  259. ]);
  260. $controller->response = new Response();
  261. $event = new Event('Controller.startup', $controller);
  262. $result = $this->component->startup($event);
  263. $this->assertNull($result, 'No error.');
  264. $this->assertEquals('testing123', $controller->request->params['_csrfToken']);
  265. }
  266. /**
  267. * Test that the configuration options work.
  268. *
  269. * @return void
  270. * @triggers Controller.startup $controller
  271. */
  272. public function testConfigurationCookieCreate()
  273. {
  274. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  275. $controller->request = new Request([
  276. 'environment' => ['REQUEST_METHOD' => 'GET'],
  277. 'webroot' => '/dir/'
  278. ]);
  279. $controller->response = new Response();
  280. $component = new CsrfComponent($this->registry, [
  281. 'cookieName' => 'token',
  282. 'expiry' => '+1 hour',
  283. 'secure' => true,
  284. 'httpOnly' => true
  285. ]);
  286. $event = new Event('Controller.startup', $controller);
  287. $component->startup($event);
  288. $this->assertEmpty($controller->response->cookie('csrfToken'));
  289. $cookie = $controller->response->cookie('token');
  290. $this->assertNotEmpty($cookie, 'Should set a token.');
  291. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  292. $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');
  293. $this->assertEquals('/dir/', $cookie['path'], 'session path.');
  294. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  295. $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');
  296. }
  297. /**
  298. * Test that the configuration options work.
  299. *
  300. * @return void
  301. * @triggers Controller.startup $controller
  302. */
  303. public function testConfigurationValidate()
  304. {
  305. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  306. $controller->request = new Request([
  307. 'environment' => ['REQUEST_METHOD' => 'POST'],
  308. 'cookies' => ['csrfToken' => 'nope', 'token' => 'yes'],
  309. 'post' => ['_csrfToken' => 'no match', 'token' => 'yes'],
  310. ]);
  311. $controller->response = new Response();
  312. $component = new CsrfComponent($this->registry, [
  313. 'cookieName' => 'token',
  314. 'field' => 'token',
  315. 'expiry' => 90,
  316. ]);
  317. $event = new Event('Controller.startup', $controller);
  318. $result = $component->startup($event);
  319. $this->assertNull($result, 'Config settings should work.');
  320. }
  321. }