CsrfComponentTest.php 12 KB

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