CsrfComponentTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. * HEAD and GET do not populate $_POST or request->data.
  77. *
  78. * @return void
  79. */
  80. public static function safeHttpMethodProvider()
  81. {
  82. return [
  83. ['GET', 'HEAD']
  84. ];
  85. }
  86. /**
  87. * Test that the CSRF tokens are not required for idempotent operations
  88. *
  89. * @dataProvider safeHttpMethodProvider
  90. * @return void
  91. */
  92. public function testSafeMethodNoCsrfRequired($method)
  93. {
  94. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  95. $controller->request = new Request([
  96. 'environment' => [
  97. 'REQUEST_METHOD' => $method,
  98. 'HTTP_X_CSRF_TOKEN' => 'nope',
  99. ],
  100. 'cookies' => ['csrfToken' => 'testing123']
  101. ]);
  102. $controller->response = new Response();
  103. $event = new Event('Controller.startup', $controller);
  104. $result = $this->component->startup($event);
  105. $this->assertNull($result, 'No exception means valid.');
  106. }
  107. /**
  108. * Data provider for HTTP methods that can contain request bodies.
  109. *
  110. * @return void
  111. */
  112. public static function httpMethodProvider()
  113. {
  114. return [
  115. ['OPTIONS'], ['PATCH'], ['PUT'], ['POST'], ['DELETE'], ['PURGE'], ['INVALIDMETHOD']
  116. ];
  117. }
  118. /**
  119. * Test that the X-CSRF-Token works with the various http methods.
  120. *
  121. * @dataProvider httpMethodProvider
  122. * @return void
  123. * @triggers Controller.startup $controller
  124. */
  125. public function testValidTokenInHeader($method)
  126. {
  127. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  128. $controller->request = new Request([
  129. 'environment' => [
  130. 'REQUEST_METHOD' => $method,
  131. 'HTTP_X_CSRF_TOKEN' => 'testing123',
  132. ],
  133. 'post' => ['a' => 'b'],
  134. 'cookies' => ['csrfToken' => 'testing123']
  135. ]);
  136. $controller->response = new Response();
  137. $event = new Event('Controller.startup', $controller);
  138. $result = $this->component->startup($event);
  139. $this->assertNull($result, 'No exception means valid.');
  140. }
  141. /**
  142. * Test that the X-CSRF-Token works with the various http methods.
  143. *
  144. * @dataProvider httpMethodProvider
  145. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  146. * @return void
  147. * @triggers Controller.startup $controller
  148. */
  149. public function testInvalidTokenInHeader($method)
  150. {
  151. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  152. $controller->request = new Request([
  153. 'environment' => [
  154. 'REQUEST_METHOD' => $method,
  155. 'HTTP_X_CSRF_TOKEN' => 'nope',
  156. ],
  157. 'post' => ['a' => 'b'],
  158. 'cookies' => ['csrfToken' => 'testing123']
  159. ]);
  160. $controller->response = new Response();
  161. $event = new Event('Controller.startup', $controller);
  162. $this->component->startup($event);
  163. }
  164. /**
  165. * Test that request data works with the various http methods.
  166. *
  167. * @dataProvider httpMethodProvider
  168. * @return void
  169. * @triggers Controller.startup $controller
  170. */
  171. public function testValidTokenRequestData($method)
  172. {
  173. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  174. $controller->request = new Request([
  175. 'environment' => [
  176. 'REQUEST_METHOD' => $method,
  177. ],
  178. 'post' => ['_csrfToken' => 'testing123'],
  179. 'cookies' => ['csrfToken' => 'testing123']
  180. ]);
  181. $controller->response = new Response();
  182. $event = new Event('Controller.startup', $controller);
  183. $result = $this->component->startup($event);
  184. $this->assertNull($result, 'No exception means valid.');
  185. $this->assertFalse(isset($controller->request->data['_csrfToken']));
  186. }
  187. /**
  188. * Test that request data works with the various http methods.
  189. *
  190. * @dataProvider httpMethodProvider
  191. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  192. * @return void
  193. */
  194. public function testInvalidTokenRequestData($method)
  195. {
  196. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  197. $controller->request = new Request([
  198. 'environment' => [
  199. 'REQUEST_METHOD' => $method,
  200. ],
  201. 'post' => ['_csrfToken' => 'nope'],
  202. 'cookies' => ['csrfToken' => 'testing123']
  203. ]);
  204. $controller->response = new Response();
  205. $event = new Event('Controller.startup', $controller);
  206. $this->component->startup($event);
  207. }
  208. /**
  209. * Test that missing post field fails
  210. *
  211. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  212. * @return void
  213. */
  214. public function testInvalidTokenRequestDataMissing()
  215. {
  216. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  217. $controller->request = new Request([
  218. 'environment' => [
  219. 'REQUEST_METHOD' => 'POST',
  220. ],
  221. 'post' => [],
  222. 'cookies' => ['csrfToken' => 'testing123']
  223. ]);
  224. $controller->response = new Response();
  225. $event = new Event('Controller.startup', $controller);
  226. $this->component->startup($event);
  227. }
  228. /**
  229. * Test that missing header and cookie fails
  230. *
  231. * @dataProvider httpMethodProvider
  232. * @expectedException \Cake\Network\Exception\InvalidCsrfTokenException
  233. * @return void
  234. */
  235. public function testInvalidTokenMissingCookie($method)
  236. {
  237. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  238. $controller->request = new Request([
  239. 'environment' => [
  240. 'REQUEST_METHOD' => $method
  241. ],
  242. 'post' => ['_csrfToken' => 'could-be-valid'],
  243. 'cookies' => []
  244. ]);
  245. $controller->response = new Response();
  246. $event = new Event('Controller.startup', $controller);
  247. $this->component->startup($event);
  248. }
  249. /**
  250. * Test that CSRF checks are not applied to request action requests.
  251. *
  252. * @return void
  253. * @triggers Controller.startup $controller
  254. */
  255. public function testCsrfValidationSkipsRequestAction()
  256. {
  257. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  258. $controller->request = new Request([
  259. 'environment' => ['REQUEST_METHOD' => 'POST'],
  260. 'params' => ['requested' => 1],
  261. 'post' => ['_csrfToken' => 'nope'],
  262. 'cookies' => ['csrfToken' => 'testing123']
  263. ]);
  264. $controller->response = new Response();
  265. $event = new Event('Controller.startup', $controller);
  266. $result = $this->component->startup($event);
  267. $this->assertNull($result, 'No error.');
  268. $this->assertEquals('testing123', $controller->request->params['_csrfToken']);
  269. }
  270. /**
  271. * Test that the configuration options work.
  272. *
  273. * @return void
  274. * @triggers Controller.startup $controller
  275. */
  276. public function testConfigurationCookieCreate()
  277. {
  278. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  279. $controller->request = new Request([
  280. 'environment' => ['REQUEST_METHOD' => 'GET'],
  281. 'webroot' => '/dir/'
  282. ]);
  283. $controller->response = new Response();
  284. $component = new CsrfComponent($this->registry, [
  285. 'cookieName' => 'token',
  286. 'expiry' => '+1 hour',
  287. 'secure' => true,
  288. 'httpOnly' => true
  289. ]);
  290. $event = new Event('Controller.startup', $controller);
  291. $component->startup($event);
  292. $this->assertEmpty($controller->response->cookie('csrfToken'));
  293. $cookie = $controller->response->cookie('token');
  294. $this->assertNotEmpty($cookie, 'Should set a token.');
  295. $this->assertRegExp('/^[a-f0-9]+$/', $cookie['value'], 'Should look like a hash.');
  296. $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');
  297. $this->assertEquals('/dir/', $cookie['path'], 'session path.');
  298. $this->assertTrue($cookie['secure'], 'cookie security flag missing');
  299. $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');
  300. }
  301. /**
  302. * Test that the configuration options work.
  303. *
  304. * @return void
  305. * @triggers Controller.startup $controller
  306. */
  307. public function testConfigurationValidate()
  308. {
  309. $controller = $this->getMock('Cake\Controller\Controller', ['redirect']);
  310. $controller->request = new Request([
  311. 'environment' => ['REQUEST_METHOD' => 'POST'],
  312. 'cookies' => ['csrfToken' => 'nope', 'token' => 'yes'],
  313. 'post' => ['_csrfToken' => 'no match', 'token' => 'yes'],
  314. ]);
  315. $controller->response = new Response();
  316. $component = new CsrfComponent($this->registry, [
  317. 'cookieName' => 'token',
  318. 'field' => 'token',
  319. 'expiry' => 90,
  320. ]);
  321. $event = new Event('Controller.startup', $controller);
  322. $result = $component->startup($event);
  323. $this->assertNull($result, 'Config settings should work.');
  324. }
  325. }