SecurityComponentTest.php 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  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 1.2.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\Component\SecurityComponent;
  17. use Cake\Controller\Controller;
  18. use Cake\Controller\Exception\SecurityException;
  19. use Cake\Core\Configure;
  20. use Cake\Event\Event;
  21. use Cake\Network\Request;
  22. use Cake\Network\Session;
  23. use Cake\TestSuite\TestCase;
  24. use Cake\Utility\Security;
  25. /**
  26. * TestSecurityComponent
  27. *
  28. */
  29. class TestSecurityComponent extends SecurityComponent
  30. {
  31. /**
  32. * validatePost method
  33. *
  34. * @param Controller $controller
  35. * @return bool
  36. */
  37. public function validatePost(Controller $controller)
  38. {
  39. return $this->_validatePost($controller);
  40. }
  41. /**
  42. * authRequired method
  43. *
  44. * @param Controller $controller
  45. * @return bool
  46. */
  47. public function authRequired(Controller $controller)
  48. {
  49. return $this->_authRequired($controller);
  50. }
  51. }
  52. /**
  53. * SecurityTestController
  54. *
  55. */
  56. class SecurityTestController extends Controller
  57. {
  58. /**
  59. * components property
  60. *
  61. * @var array
  62. */
  63. public $components = [
  64. 'TestSecurity' => ['className' => 'Cake\Test\TestCase\Controller\Component\TestSecurityComponent']
  65. ];
  66. /**
  67. * failed property
  68. *
  69. * @var bool
  70. */
  71. public $failed = false;
  72. /**
  73. * Used for keeping track of headers in test
  74. *
  75. * @var array
  76. */
  77. public $testHeaders = [];
  78. /**
  79. * fail method
  80. *
  81. * @return void
  82. */
  83. public function fail()
  84. {
  85. $this->failed = true;
  86. }
  87. /**
  88. * redirect method
  89. *
  90. * @param string|array $url
  91. * @param mixed $status
  92. * @param mixed $exit
  93. * @return void
  94. */
  95. public function redirect($url, $status = null, $exit = true)
  96. {
  97. return $status;
  98. }
  99. /**
  100. * Convenience method for header()
  101. *
  102. * @param string $status
  103. * @return void
  104. */
  105. public function header($status)
  106. {
  107. $this->testHeaders[] = $status;
  108. }
  109. }
  110. /**
  111. * SecurityComponentTest class
  112. *
  113. * @property SecurityComponent Security
  114. * @property SecurityTestController Controller
  115. */
  116. class SecurityComponentTest extends TestCase
  117. {
  118. /**
  119. * Controller property
  120. *
  121. * @var SecurityTestController
  122. */
  123. public $Controller;
  124. /**
  125. * oldSalt property
  126. *
  127. * @var string
  128. */
  129. public $oldSalt;
  130. /**
  131. * setUp method
  132. *
  133. * @return void
  134. */
  135. public function setUp()
  136. {
  137. parent::setUp();
  138. $session = new Session();
  139. $request = $this->getMockBuilder('Cake\Network\Request')
  140. ->setMethods(['here'])
  141. ->setConstructorArgs(['posts/index'])
  142. ->getMock();
  143. $request->addParams(['controller' => 'posts', 'action' => 'index']);
  144. $request->session($session);
  145. $request->expects($this->any())
  146. ->method('here')
  147. ->will($this->returnValue('/articles/index'));
  148. $this->Controller = new SecurityTestController($request);
  149. $this->Controller->Security = $this->Controller->TestSecurity;
  150. $this->Controller->Security->config('blackHoleCallback', 'fail');
  151. $this->Security = $this->Controller->Security;
  152. $this->Security->session = $session;
  153. Security::salt('foo!');
  154. }
  155. /**
  156. * Tear-down method. Resets environment state.
  157. *
  158. * @return void
  159. */
  160. public function tearDown()
  161. {
  162. parent::tearDown();
  163. $this->Security->session->delete('_Token');
  164. unset($this->Controller->Security);
  165. unset($this->Controller->Component);
  166. unset($this->Controller);
  167. }
  168. public function validatePost($expectedException = null, $expectedExceptionMessage = null)
  169. {
  170. try {
  171. return $this->Controller->Security->validatePost($this->Controller);
  172. } catch (SecurityException $ex) {
  173. $this->assertInstanceOf('Cake\\Controller\\Exception\\' . $expectedException, $ex);
  174. $this->assertEquals($expectedExceptionMessage, $ex->getMessage());
  175. return false;
  176. }
  177. }
  178. /**
  179. * Test that requests are still blackholed when controller has incorrect
  180. * visibility keyword in the blackhole callback
  181. *
  182. * @expectedException \Cake\Network\Exception\BadRequestException
  183. * @return void
  184. * @triggers Controller.startup $Controller, $this->Controller
  185. */
  186. public function testBlackholeWithBrokenCallback()
  187. {
  188. $request = new Request([
  189. 'url' => 'posts/index',
  190. 'session' => $this->Security->session
  191. ]);
  192. $request->addParams([
  193. 'controller' => 'posts',
  194. 'action' => 'index'
  195. ]);
  196. $Controller = new \TestApp\Controller\SomePagesController($request);
  197. $event = new Event('Controller.startup', $Controller, $this->Controller);
  198. $Security = new SecurityComponent($Controller->components());
  199. $Security->config('blackHoleCallback', '_fail');
  200. $Security->startup($event);
  201. $Security->blackHole($Controller, 'csrf');
  202. }
  203. /**
  204. * Ensure that directly requesting the blackholeCallback as the controller
  205. * action results in an exception.
  206. *
  207. * @return void
  208. * @triggers Controller.startup $this->Controller
  209. */
  210. public function testExceptionWhenActionIsBlackholeCallback()
  211. {
  212. $this->Controller->request->addParams([
  213. 'controller' => 'posts',
  214. 'action' => 'fail'
  215. ]);
  216. $event = new Event('Controller.startup', $this->Controller);
  217. $this->assertFalse($this->Controller->failed);
  218. $this->Controller->Security->startup($event);
  219. $this->assertTrue($this->Controller->failed, 'Request was blackholed.');
  220. }
  221. /**
  222. * test that initialize can set properties.
  223. *
  224. * @return void
  225. */
  226. public function testConstructorSettingProperties()
  227. {
  228. $settings = [
  229. 'requireSecure' => ['update_account'],
  230. 'validatePost' => false,
  231. ];
  232. $Security = new SecurityComponent($this->Controller->components(), $settings);
  233. $this->assertEquals($Security->validatePost, $settings['validatePost']);
  234. }
  235. /**
  236. * testStartup method
  237. *
  238. * @return void
  239. * @triggers Controller.startup $this->Controller
  240. */
  241. public function testStartup()
  242. {
  243. $event = new Event('Controller.startup', $this->Controller);
  244. $this->Controller->Security->startup($event);
  245. $this->assertTrue($this->Security->session->check('_Token'));
  246. }
  247. /**
  248. * testRequireSecureFail method
  249. *
  250. * @return void
  251. * @triggers Controller.startup $this->Controller
  252. */
  253. public function testRequireSecureFail()
  254. {
  255. $_SERVER['HTTPS'] = 'off';
  256. $_SERVER['REQUEST_METHOD'] = 'POST';
  257. $this->Controller->request['action'] = 'posted';
  258. $event = new Event('Controller.startup', $this->Controller);
  259. $this->Controller->Security->requireSecure(['posted']);
  260. $this->Controller->Security->startup($event);
  261. $this->assertTrue($this->Controller->failed);
  262. }
  263. /**
  264. * testRequireSecureSucceed method
  265. *
  266. * @return void
  267. * @triggers Controller.startup $this->Controller
  268. */
  269. public function testRequireSecureSucceed()
  270. {
  271. $_SERVER['HTTPS'] = 'on';
  272. $_SERVER['REQUEST_METHOD'] = 'Secure';
  273. $this->Controller->request['action'] = 'posted';
  274. $event = new Event('Controller.startup', $this->Controller);
  275. $this->Controller->Security->requireSecure('posted');
  276. $this->Controller->Security->startup($event);
  277. $this->assertFalse($this->Controller->failed);
  278. }
  279. /**
  280. * testRequireSecureEmptyFail method
  281. *
  282. * @return void
  283. * @triggers Controller.startup $this->Controller
  284. */
  285. public function testRequireSecureEmptyFail()
  286. {
  287. $_SERVER['HTTPS'] = 'off';
  288. $_SERVER['REQUEST_METHOD'] = 'POST';
  289. $this->Controller->request['action'] = 'posted';
  290. $event = new Event('Controller.startup', $this->Controller);
  291. $this->Controller->Security->requireSecure();
  292. $this->Controller->Security->startup($event);
  293. $this->assertTrue($this->Controller->failed);
  294. }
  295. /**
  296. * testRequireSecureEmptySucceed method
  297. *
  298. * @return void
  299. * @triggers Controller.startup $this->Controller
  300. */
  301. public function testRequireSecureEmptySucceed()
  302. {
  303. $_SERVER['HTTPS'] = 'on';
  304. $_SERVER['REQUEST_METHOD'] = 'Secure';
  305. $this->Controller->request['action'] = 'posted';
  306. $event = new Event('Controller.startup', $this->Controller);
  307. $this->Controller->Security->requireSecure();
  308. $this->Controller->Security->startup($event);
  309. $this->assertFalse($this->Controller->failed);
  310. }
  311. /**
  312. * testRequireAuthFail method
  313. *
  314. * @return void
  315. * @triggers Controller.startup $this->Controller
  316. */
  317. public function testRequireAuthFail()
  318. {
  319. $event = new Event('Controller.startup', $this->Controller);
  320. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  321. $this->Controller->request['action'] = 'posted';
  322. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  323. $this->Controller->Security->requireAuth(['posted']);
  324. $this->Controller->Security->startup($event);
  325. $this->assertTrue($this->Controller->failed);
  326. $this->Security->session->write('_Token', ['allowedControllers' => []]);
  327. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  328. $this->Controller->request['action'] = 'posted';
  329. $this->Controller->Security->requireAuth('posted');
  330. $this->Controller->Security->startup($event);
  331. $this->assertTrue($this->Controller->failed);
  332. $this->Security->session->write('_Token', [
  333. 'allowedControllers' => ['SecurityTest'], 'allowedActions' => ['posted2']
  334. ]);
  335. $this->Controller->request->data = ['username' => 'willy', 'password' => 'somePass'];
  336. $this->Controller->request['action'] = 'posted';
  337. $this->Controller->Security->requireAuth('posted');
  338. $this->Controller->Security->startup($event);
  339. $this->assertTrue($this->Controller->failed);
  340. }
  341. /**
  342. * testRequireAuthSucceed method
  343. *
  344. * @return void
  345. * @triggers Controller.startup $this->Controller
  346. */
  347. public function testRequireAuthSucceed()
  348. {
  349. $_SERVER['REQUEST_METHOD'] = 'AUTH';
  350. $this->Controller->Security->config('validatePost', false);
  351. $event = new Event('Controller.startup', $this->Controller);
  352. $this->Controller->request['action'] = 'posted';
  353. $this->Controller->Security->requireAuth('posted');
  354. $this->Controller->Security->startup($event);
  355. $this->assertFalse($this->Controller->failed);
  356. $this->Controller->Security->session->write('_Token', [
  357. 'allowedControllers' => ['SecurityTest'],
  358. 'allowedActions' => ['posted'],
  359. ]);
  360. $this->Controller->request['controller'] = 'SecurityTest';
  361. $this->Controller->request['action'] = 'posted';
  362. $this->Controller->request->data = [
  363. 'username' => 'willy',
  364. 'password' => 'somePass',
  365. '_Token' => ''
  366. ];
  367. $this->Controller->action = 'posted';
  368. $this->Controller->Security->requireAuth('posted');
  369. $this->Controller->Security->startup($event);
  370. $this->assertFalse($this->Controller->failed);
  371. }
  372. /**
  373. * Simple hash validation test
  374. *
  375. * @return void
  376. * @triggers Controller.startup $this->Controller
  377. */
  378. public function testValidatePost()
  379. {
  380. $event = new Event('Controller.startup', $this->Controller);
  381. $this->Controller->Security->startup($event);
  382. $fields = '68730b0747d4889ec2766f9117405f9635f5fd5e%3AModel.valid';
  383. $unlocked = '';
  384. $debug = '';
  385. $this->Controller->request->data = [
  386. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  387. '_Token' => compact('fields', 'unlocked', 'debug'),
  388. ];
  389. $this->assertTrue($this->validatePost());
  390. }
  391. /**
  392. * Test that validatePost fires on GET with request data.
  393. * This could happen when method overriding is used.
  394. *
  395. * @return void
  396. * @triggers Controller.startup $this->Controller
  397. */
  398. public function testValidatePostOnGetWithData()
  399. {
  400. $event = new Event('Controller.startup', $this->Controller);
  401. $this->Controller->Security->startup($event);
  402. $fields = 'an-invalid-token';
  403. $unlocked = '';
  404. $debug = urlencode(json_encode([
  405. 'some-action',
  406. [],
  407. []
  408. ]));
  409. $this->Controller->request->env('REQUEST_METHOD', 'GET');
  410. $this->Controller->request->data = [
  411. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  412. '_Token' => compact('fields', 'unlocked', 'debug')
  413. ];
  414. $this->Controller->Security->startup($event);
  415. $this->assertTrue($this->Controller->failed);
  416. }
  417. /**
  418. * Test that validatePost fails if you are missing the session information.
  419. *
  420. * @return void
  421. * @triggers Controller.startup $this->Controller
  422. */
  423. public function testValidatePostNoSession()
  424. {
  425. $event = new Event('Controller.startup', $this->Controller);
  426. $this->Controller->Security->startup($event);
  427. $this->Security->session->delete('_Token');
  428. $unlocked = '';
  429. $debug = urlencode(json_encode([
  430. '/articles/index',
  431. [],
  432. []
  433. ]));
  434. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  435. $this->Controller->request->data = [
  436. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  437. '_Token' => compact('fields', 'unlocked', 'debug')
  438. ];
  439. $this->assertFalse($this->validatePost('AuthSecurityException', 'Unexpected field \'Model.password\' in POST data, Unexpected field \'Model.username\' in POST data'));
  440. }
  441. /**
  442. * Test that validatePost fails if you are missing unlocked in request data.
  443. *
  444. * @return void
  445. * @triggers Controller.startup $this->Controller
  446. */
  447. public function testValidatePostNoUnlockedInRequestData()
  448. {
  449. $event = new Event('Controller.startup', $this->Controller);
  450. $this->Controller->Security->startup($event);
  451. $this->Security->session->delete('_Token');
  452. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
  453. $this->Controller->request->data = [
  454. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  455. '_Token' => compact('fields')
  456. ];
  457. $this->assertFalse($this->validatePost('AuthSecurityException', '\'_Token.unlocked\' was not found in request data.'));
  458. }
  459. /**
  460. * test that validatePost fails if any of its required fields are missing.
  461. *
  462. * @return void
  463. * @triggers Controller.startup $this->Controller
  464. */
  465. public function testValidatePostFormHacking()
  466. {
  467. $event = new Event('Controller.startup', $this->Controller);
  468. $this->Controller->Security->startup($event);
  469. $unlocked = '';
  470. $this->Controller->request->data = [
  471. 'Model' => ['username' => 'nate', 'password' => 'foo', 'valid' => '0'],
  472. '_Token' => compact('unlocked')
  473. ];
  474. $result = $this->validatePost('AuthSecurityException', '\'_Token.fields\' was not found in request data.');
  475. $this->assertFalse($result, 'validatePost passed when fields were missing. %s');
  476. }
  477. /**
  478. * Test that objects can't be passed into the serialized string. This was a vector for RFI and LFI
  479. * attacks. Thanks to Felix Wilhelm
  480. *
  481. * @return void
  482. * @triggers Controller.startup $this->Controller
  483. */
  484. public function testValidatePostObjectDeserialize()
  485. {
  486. $event = new Event('Controller.startup', $this->Controller);
  487. $this->Controller->Security->startup($event);
  488. $fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877';
  489. $unlocked = '';
  490. $debug = urlencode(json_encode([
  491. '/articles/index',
  492. ['Model.password', 'Model.username', 'Model.valid'],
  493. []
  494. ]));
  495. // a corrupted serialized object, so we can see if it ever gets to deserialize
  496. $attack = 'O:3:"App":1:{s:5:"__map";a:1:{s:3:"foo";s:7:"Hacked!";s:1:"fail"}}';
  497. $fields .= urlencode(':' . str_rot13($attack));
  498. $this->Controller->request->data = [
  499. 'Model' => ['username' => 'mark', 'password' => 'foo', 'valid' => '0'],
  500. '_Token' => compact('fields', 'unlocked', 'debug')
  501. ];
  502. $result = $this->validatePost('SecurityException', 'Bad Request');
  503. $this->assertFalse($result, 'validatePost passed when key was missing. %s');
  504. }
  505. /**
  506. * Tests validation post data ignores `_csrfToken`.
  507. *
  508. * @return void
  509. * @triggers Controller.startup $this->Controller
  510. */
  511. public function testValidatePostIgnoresCsrfToken()
  512. {
  513. $event = new Event('Controller.startup', $this->Controller);
  514. $this->Controller->Security->startup($event);
  515. $fields = '8e26ef05379e5402c2c619f37ee91152333a0264%3A';
  516. $unlocked = '';
  517. $debug = 'not used';
  518. $this->Controller->request->data = [
  519. '_csrfToken' => 'abc123',
  520. 'Model' => ['multi_field' => ['1', '3']],
  521. '_Token' => compact('fields', 'unlocked', 'debug')
  522. ];
  523. $this->assertTrue($this->validatePost());
  524. }
  525. /**
  526. * Tests validation of checkbox arrays
  527. *
  528. * @return void
  529. * @triggers Controller.startup $this->Controller
  530. */
  531. public function testValidatePostArray()
  532. {
  533. $event = new Event('Controller.startup', $this->Controller);
  534. $this->Controller->Security->startup($event);
  535. $fields = '8e26ef05379e5402c2c619f37ee91152333a0264%3A';
  536. $unlocked = '';
  537. $debug = urlencode(json_encode([
  538. 'some-action',
  539. [],
  540. []
  541. ]));
  542. $this->Controller->request->data = [
  543. 'Model' => ['multi_field' => ['1', '3']],
  544. '_Token' => compact('fields', 'unlocked', 'debug')
  545. ];
  546. $this->assertTrue($this->validatePost());
  547. $this->Controller->request->data = [
  548. 'Model' => ['multi_field' => [12 => '1', 20 => '3']],
  549. '_Token' => compact('fields', 'unlocked', 'debug')
  550. ];
  551. $this->assertTrue($this->validatePost());
  552. }
  553. /**
  554. * Tests validation of integer field names.
  555. *
  556. * @return void
  557. */
  558. public function testValidateIntFieldName()
  559. {
  560. $event = new Event('Controller.startup', $this->Controller);
  561. $this->Controller->Security->startup($event);
  562. $fields = '4a221010dd7a23f7166cb10c38bc21d81341c387%3A';
  563. $unlocked = '';
  564. $debug = urlencode(json_encode([
  565. 'some-action',
  566. [],
  567. []
  568. ]));
  569. $this->Controller->request->data = [
  570. 1 => 'value,',
  571. '_Token' => compact('fields', 'unlocked', 'debug')
  572. ];
  573. $this->assertTrue($this->validatePost());
  574. }
  575. /**
  576. * testValidatePostNoModel method
  577. *
  578. * @return void
  579. * @triggers Controller.startup $this->Controller
  580. */
  581. public function testValidatePostNoModel()
  582. {
  583. $event = new Event('Controller.startup', $this->Controller);
  584. $this->Controller->Security->startup($event);
  585. $fields = 'a1c3724b7ba85e7022413611e30ba2c6181d5aba%3A';
  586. $unlocked = '';
  587. $debug = 'not used';
  588. $this->Controller->request->data = [
  589. 'anything' => 'some_data',
  590. '_Token' => compact('fields', 'unlocked', 'debug')
  591. ];
  592. $result = $this->validatePost();
  593. $this->assertTrue($result);
  594. }
  595. /**
  596. * testValidatePostSimple method
  597. *
  598. * @return void
  599. * @triggers Controller.startup $this->Controller
  600. */
  601. public function testValidatePostSimple()
  602. {
  603. $event = new Event('Controller.startup', $this->Controller);
  604. $this->Controller->Security->startup($event);
  605. $fields = 'b0914d06dfb04abf1fada53e16810e87d157950b%3A';
  606. $unlocked = '';
  607. $debug = 'not used';
  608. $this->Controller->request->data = [
  609. 'Model' => ['username' => '', 'password' => ''],
  610. '_Token' => compact('fields', 'unlocked', 'debug')
  611. ];
  612. $result = $this->validatePost();
  613. $this->assertTrue($result);
  614. }
  615. /**
  616. * Tests hash validation for multiple records, including locked fields
  617. *
  618. * @return void
  619. * @triggers Controller.startup $this->Controller
  620. */
  621. public function testValidatePostComplex()
  622. {
  623. $event = new Event('Controller.startup', $this->Controller);
  624. $this->Controller->Security->startup($event);
  625. $fields = 'b65c7463e44a61d8d2eaecce2c265b406c9c4742%3AAddresses.0.id%7CAddresses.1.id';
  626. $unlocked = '';
  627. $debug = 'not used';
  628. $this->Controller->request->data = [
  629. 'Addresses' => [
  630. '0' => [
  631. 'id' => '123456', 'title' => '', 'first_name' => '', 'last_name' => '',
  632. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  633. ],
  634. '1' => [
  635. 'id' => '654321', 'title' => '', 'first_name' => '', 'last_name' => '',
  636. 'address' => '', 'city' => '', 'phone' => '', 'primary' => ''
  637. ]
  638. ],
  639. '_Token' => compact('fields', 'unlocked', 'debug')
  640. ];
  641. $result = $this->validatePost();
  642. $this->assertTrue($result);
  643. }
  644. /**
  645. * test ValidatePost with multiple select elements.
  646. *
  647. * @return void
  648. * @triggers Controller.startup $this->Controller
  649. */
  650. public function testValidatePostMultipleSelect()
  651. {
  652. $event = new Event('Controller.startup', $this->Controller);
  653. $this->Controller->Security->startup($event);
  654. $fields = '8d8da68ba03b3d6e7e145b948abfe26741422169%3A';
  655. $unlocked = '';
  656. $debug = 'not used';
  657. $this->Controller->request->data = [
  658. 'Tag' => ['Tag' => [1, 2]],
  659. '_Token' => compact('fields', 'unlocked', 'debug'),
  660. ];
  661. $result = $this->validatePost();
  662. $this->assertTrue($result);
  663. $this->Controller->request->data = [
  664. 'Tag' => ['Tag' => [1, 2, 3]],
  665. '_Token' => compact('fields', 'unlocked', 'debug'),
  666. ];
  667. $result = $this->validatePost();
  668. $this->assertTrue($result);
  669. $this->Controller->request->data = [
  670. 'Tag' => ['Tag' => [1, 2, 3, 4]],
  671. '_Token' => compact('fields', 'unlocked', 'debug'),
  672. ];
  673. $result = $this->validatePost();
  674. $this->assertTrue($result);
  675. $fields = 'eae2adda1628b771a30cc133342d16220c6520fe%3A';
  676. $this->Controller->request->data = [
  677. 'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1',
  678. 'Tag' => ['Tag' => [1]],
  679. '_Token' => compact('fields', 'unlocked', 'debug'),
  680. ];
  681. $result = $this->validatePost();
  682. $this->assertTrue($result);
  683. }
  684. /**
  685. * testValidatePostCheckbox method
  686. *
  687. * First block tests un-checked checkbox
  688. * Second block tests checked checkbox
  689. *
  690. * @return void
  691. * @triggers Controller.startup $this->Controller
  692. */
  693. public function testValidatePostCheckbox()
  694. {
  695. $event = new Event('Controller.startup', $this->Controller);
  696. $this->Controller->Security->startup($event);
  697. $fields = '68730b0747d4889ec2766f9117405f9635f5fd5e%3AModel.valid';
  698. $unlocked = '';
  699. $debug = 'not used';
  700. $this->Controller->request->data = [
  701. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  702. '_Token' => compact('fields', 'unlocked', 'debug'),
  703. ];
  704. $result = $this->validatePost();
  705. $this->assertTrue($result);
  706. $fields = 'f63e4a69b2edd31f064e8e602a04dd59307cfe9c%3A';
  707. $this->Controller->request->data = [
  708. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  709. '_Token' => compact('fields', 'unlocked', 'debug'),
  710. ];
  711. $result = $this->validatePost();
  712. $this->assertTrue($result);
  713. $this->Controller->request->data = [];
  714. $this->Controller->Security->startup($event);
  715. $this->Controller->request->data = [
  716. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  717. '_Token' => compact('fields', 'unlocked', 'debug'),
  718. ];
  719. $result = $this->validatePost();
  720. $this->assertTrue($result);
  721. }
  722. /**
  723. * testValidatePostHidden method
  724. *
  725. * @return void
  726. * @triggers Controller.startup $this->Controller
  727. */
  728. public function testValidatePostHidden()
  729. {
  730. $event = new Event('Controller.startup', $this->Controller);
  731. $this->Controller->Security->startup($event);
  732. $fields = '973a8939a68ac014cc6f7666cec9aa6268507350%3AModel.hidden%7CModel.other_hidden';
  733. $unlocked = '';
  734. $debug = 'not used';
  735. $this->Controller->request->data = [
  736. 'Model' => [
  737. 'username' => '', 'password' => '', 'hidden' => '0',
  738. 'other_hidden' => 'some hidden value'
  739. ],
  740. '_Token' => compact('fields', 'unlocked', 'debug'),
  741. ];
  742. $result = $this->validatePost();
  743. $this->assertTrue($result);
  744. }
  745. /**
  746. * testValidatePostWithDisabledFields method
  747. *
  748. * @return void
  749. * @triggers Controller.startup $this->Controller
  750. */
  751. public function testValidatePostWithDisabledFields()
  752. {
  753. $event = new Event('Controller.startup', $this->Controller);
  754. $this->Controller->Security->config('disabledFields', ['Model.username', 'Model.password']);
  755. $this->Controller->Security->startup($event);
  756. $fields = '1c59acfbca98bd870c11fb544d545cbf23215880%3AModel.hidden';
  757. $unlocked = '';
  758. $debug = 'not used';
  759. $this->Controller->request->data = [
  760. 'Model' => [
  761. 'username' => '', 'password' => '', 'hidden' => '0'
  762. ],
  763. '_Token' => compact('fields', 'unlocked', 'debug'),
  764. ];
  765. $result = $this->validatePost();
  766. $this->assertTrue($result);
  767. }
  768. /**
  769. * test validating post data with posted unlocked fields.
  770. *
  771. * @return void
  772. * @triggers Controller.startup $this->Controller
  773. */
  774. public function testValidatePostDisabledFieldsInData()
  775. {
  776. $event = new Event('Controller.startup', $this->Controller);
  777. $this->Controller->Security->startup($event);
  778. $unlocked = 'Model.username';
  779. $fields = ['Model.hidden', 'Model.password'];
  780. $fields = urlencode(Security::hash('/articles/index' . serialize($fields) . $unlocked . Security::salt()));
  781. $debug = 'not used';
  782. $this->Controller->request->data = [
  783. 'Model' => [
  784. 'username' => 'mark',
  785. 'password' => 'sekret',
  786. 'hidden' => '0'
  787. ],
  788. '_Token' => compact('fields', 'unlocked', 'debug'),
  789. ];
  790. $result = $this->validatePost();
  791. $this->assertTrue($result);
  792. }
  793. /**
  794. * test that missing 'unlocked' input causes failure
  795. *
  796. * @return void
  797. * @triggers Controller.startup $this->Controller
  798. */
  799. public function testValidatePostFailNoDisabled()
  800. {
  801. $event = new Event('Controller.startup', $this->Controller);
  802. $this->Controller->Security->startup($event);
  803. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  804. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  805. $this->Controller->request->data = [
  806. 'Model' => [
  807. 'username' => 'mark',
  808. 'password' => 'sekret',
  809. 'hidden' => '0'
  810. ],
  811. '_Token' => compact('fields')
  812. ];
  813. $result = $this->validatePost('SecurityException', '\'_Token.unlocked\' was not found in request data.');
  814. $this->assertFalse($result);
  815. }
  816. /**
  817. * test that missing 'debug' input causes failure
  818. *
  819. * @return void
  820. * @triggers Controller.startup $this->Controller
  821. */
  822. public function testValidatePostFailNoDebug()
  823. {
  824. $event = new Event('Controller.startup', $this->Controller);
  825. $this->Controller->Security->startup($event);
  826. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  827. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  828. $unlocked = '';
  829. $this->Controller->request->data = [
  830. 'Model' => [
  831. 'username' => 'mark',
  832. 'password' => 'sekret',
  833. 'hidden' => '0'
  834. ],
  835. '_Token' => compact('fields', 'unlocked')
  836. ];
  837. $result = $this->validatePost('SecurityException', '\'_Token.debug\' was not found in request data.');
  838. $this->assertFalse($result);
  839. }
  840. /**
  841. * test that missing 'debug' input is not the problem when debug mode disabled
  842. *
  843. * @return void
  844. * @triggers Controller.startup $this->Controller
  845. */
  846. public function testValidatePostFailNoDebugMode()
  847. {
  848. $event = new Event('Controller.startup', $this->Controller);
  849. $this->Controller->Security->startup($event);
  850. $fields = ['Model.hidden', 'Model.password', 'Model.username'];
  851. $fields = urlencode(Security::hash(serialize($fields) . Security::salt()));
  852. $unlocked = '';
  853. $this->Controller->request->data = [
  854. 'Model' => [
  855. 'username' => 'mark',
  856. 'password' => 'sekret',
  857. 'hidden' => '0'
  858. ],
  859. '_Token' => compact('fields', 'unlocked')
  860. ];
  861. Configure::write('debug', false);
  862. $result = $this->validatePost('SecurityException', 'The request has been black-holed');
  863. }
  864. /**
  865. * Test that validatePost fails when unlocked fields are changed.
  866. *
  867. * @return void
  868. * @triggers Controller.startup $this->Controller
  869. */
  870. public function testValidatePostFailDisabledFieldTampering()
  871. {
  872. $event = new Event('Controller.startup', $this->Controller);
  873. $this->Controller->Security->startup($event);
  874. $unlocked = 'Model.username';
  875. $fields = ['Model.hidden', 'Model.password'];
  876. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  877. $debug = urlencode(json_encode([
  878. '/articles/index',
  879. ['Model.hidden', 'Model.password'],
  880. ['Model.username']
  881. ]));
  882. // Tamper the values.
  883. $unlocked = 'Model.username|Model.password';
  884. $this->Controller->request->data = [
  885. 'Model' => [
  886. 'username' => 'mark',
  887. 'password' => 'sekret',
  888. 'hidden' => '0'
  889. ],
  890. '_Token' => compact('fields', 'unlocked', 'debug')
  891. ];
  892. $result = $this->validatePost('SecurityException', 'Missing field \'Model.password\' in POST data, Unexpected unlocked field \'Model.password\' in POST data');
  893. $this->assertFalse($result);
  894. }
  895. /**
  896. * testValidateHiddenMultipleModel method
  897. *
  898. * @return void
  899. * @triggers Controller.startup $this->Controller
  900. */
  901. public function testValidateHiddenMultipleModel()
  902. {
  903. $event = new Event('Controller.startup', $this->Controller);
  904. $this->Controller->Security->startup($event);
  905. $fields = '075ca6c26c38a09a78d871201df89faf52cbbeb8%3AModel.valid%7CModel2.valid%7CModel3.valid';
  906. $unlocked = '';
  907. $debug = 'not used';
  908. $this->Controller->request->data = [
  909. 'Model' => ['username' => '', 'password' => '', 'valid' => '0'],
  910. 'Model2' => ['valid' => '0'],
  911. 'Model3' => ['valid' => '0'],
  912. '_Token' => compact('fields', 'unlocked', 'debug'),
  913. ];
  914. $result = $this->validatePost();
  915. $this->assertTrue($result);
  916. }
  917. /**
  918. * testValidateHasManyModel method
  919. *
  920. * @return void
  921. * @triggers Controller.startup $this->Controller
  922. */
  923. public function testValidateHasManyModel()
  924. {
  925. $event = new Event('Controller.startup', $this->Controller);
  926. $this->Controller->Security->startup($event);
  927. $fields = '24a753fb62ef7839389987b58e3f7108f564e529%3AModel.0.hidden%7CModel.0.valid';
  928. $fields .= '%7CModel.1.hidden%7CModel.1.valid';
  929. $unlocked = '';
  930. $debug = 'not used';
  931. $this->Controller->request->data = [
  932. 'Model' => [
  933. [
  934. 'username' => 'username', 'password' => 'password',
  935. 'hidden' => 'value', 'valid' => '0'
  936. ],
  937. [
  938. 'username' => 'username', 'password' => 'password',
  939. 'hidden' => 'value', 'valid' => '0'
  940. ]
  941. ],
  942. '_Token' => compact('fields', 'unlocked', 'debug'),
  943. ];
  944. $result = $this->validatePost();
  945. $this->assertTrue($result);
  946. }
  947. /**
  948. * testValidateHasManyRecordsPass method
  949. *
  950. * @return void
  951. * @triggers Controller.startup $this->Controller
  952. */
  953. public function testValidateHasManyRecordsPass()
  954. {
  955. $event = new Event('Controller.startup', $this->Controller);
  956. $this->Controller->Security->startup($event);
  957. $fields = '8f7d82bf7656cf068822d9bdab109ebed1be1825%3AAddress.0.id%7CAddress.0.primary%7C';
  958. $fields .= 'Address.1.id%7CAddress.1.primary';
  959. $unlocked = '';
  960. $debug = 'not used';
  961. $this->Controller->request->data = [
  962. 'Address' => [
  963. 0 => [
  964. 'id' => '123',
  965. 'title' => 'home',
  966. 'first_name' => 'Bilbo',
  967. 'last_name' => 'Baggins',
  968. 'address' => '23 Bag end way',
  969. 'city' => 'the shire',
  970. 'phone' => 'N/A',
  971. 'primary' => '1',
  972. ],
  973. 1 => [
  974. 'id' => '124',
  975. 'title' => 'home',
  976. 'first_name' => 'Frodo',
  977. 'last_name' => 'Baggins',
  978. 'address' => '50 Bag end way',
  979. 'city' => 'the shire',
  980. 'phone' => 'N/A',
  981. 'primary' => '1'
  982. ]
  983. ],
  984. '_Token' => compact('fields', 'unlocked', 'debug'),
  985. ];
  986. $result = $this->validatePost();
  987. $this->assertTrue($result);
  988. }
  989. /**
  990. * Test that values like Foo.0.1
  991. *
  992. * @return void
  993. * @triggers Controller.startup $this->Controller
  994. */
  995. public function testValidateNestedNumericSets()
  996. {
  997. $event = new Event('Controller.startup', $this->Controller);
  998. $this->Controller->Security->startup($event);
  999. $unlocked = '';
  1000. $hashFields = ['TaxonomyData'];
  1001. $fields = urlencode(Security::hash('/articles/index' . serialize($hashFields) . $unlocked . Security::salt()));
  1002. $debug = 'not used';
  1003. $this->Controller->request->data = [
  1004. 'TaxonomyData' => [
  1005. 1 => [[2]],
  1006. 2 => [[3]]
  1007. ],
  1008. '_Token' => compact('fields', 'unlocked', 'debug'),
  1009. ];
  1010. $result = $this->validatePost();
  1011. $this->assertTrue($result);
  1012. }
  1013. /**
  1014. * testValidateHasManyRecords method
  1015. *
  1016. * validatePost should fail, hidden fields have been changed.
  1017. *
  1018. * @return void
  1019. * @triggers Controller.startup $this->Controller
  1020. */
  1021. public function testValidateHasManyRecordsFail()
  1022. {
  1023. $event = new Event('Controller.startup', $this->Controller);
  1024. $this->Controller->Security->startup($event);
  1025. $fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C';
  1026. $fields .= 'Address.1.id%7CAddress.1.primary';
  1027. $unlocked = '';
  1028. $debug = urlencode(json_encode([
  1029. '/articles/index',
  1030. [
  1031. 'Address.0.address',
  1032. 'Address.0.city',
  1033. 'Address.0.first_name',
  1034. 'Address.0.last_name',
  1035. 'Address.0.phone',
  1036. 'Address.0.title',
  1037. 'Address.1.address',
  1038. 'Address.1.city',
  1039. 'Address.1.first_name',
  1040. 'Address.1.last_name',
  1041. 'Address.1.phone',
  1042. 'Address.1.title',
  1043. 'Address.0.id' => '123',
  1044. 'Address.0.primary' => '5',
  1045. 'Address.1.id' => '124',
  1046. 'Address.1.primary' => '1'
  1047. ],
  1048. []
  1049. ]));
  1050. $this->Controller->request->data = [
  1051. 'Address' => [
  1052. 0 => [
  1053. 'id' => '123',
  1054. 'title' => 'home',
  1055. 'first_name' => 'Bilbo',
  1056. 'last_name' => 'Baggins',
  1057. 'address' => '23 Bag end way',
  1058. 'city' => 'the shire',
  1059. 'phone' => 'N/A',
  1060. 'primary' => '5',
  1061. ],
  1062. 1 => [
  1063. 'id' => '124',
  1064. 'title' => 'home',
  1065. 'first_name' => 'Frodo',
  1066. 'last_name' => 'Baggins',
  1067. 'address' => '50 Bag end way',
  1068. 'city' => 'the shire',
  1069. 'phone' => 'N/A',
  1070. 'primary' => '1'
  1071. ]
  1072. ],
  1073. '_Token' => compact('fields', 'unlocked', 'debug'),
  1074. ];
  1075. $result = $this->validatePost('SecurityException', 'Bad Request');
  1076. $this->assertFalse($result);
  1077. }
  1078. /**
  1079. * testFormDisabledFields method
  1080. *
  1081. * @return void
  1082. * @triggers Controller.startup $this->Controller
  1083. */
  1084. public function testFormDisabledFields()
  1085. {
  1086. $event = new Event('Controller.startup', $this->Controller);
  1087. $this->Controller->Security->startup($event);
  1088. $fields = '9da2b3fa2b5b8ac0bfbc1bbce145e58059629125%3An%3A0%3A%7B%7D';
  1089. $unlocked = '';
  1090. $debug = urlencode(json_encode([
  1091. '/articles/index',
  1092. [],
  1093. []
  1094. ]));
  1095. $this->Controller->request->data = [
  1096. 'MyModel' => ['name' => 'some data'],
  1097. '_Token' => compact('fields', 'unlocked', 'debug'),
  1098. ];
  1099. $result = $this->validatePost('SecurityException', 'Unexpected field \'MyModel.name\' in POST data');
  1100. $this->assertFalse($result);
  1101. $this->Controller->Security->startup($event);
  1102. $this->Controller->Security->config('disabledFields', ['MyModel.name']);
  1103. $this->Controller->request->data = [
  1104. 'MyModel' => ['name' => 'some data'],
  1105. '_Token' => compact('fields', 'unlocked', 'debug'),
  1106. ];
  1107. $result = $this->validatePost();
  1108. $this->assertTrue($result);
  1109. }
  1110. /**
  1111. * test validatePost with radio buttons
  1112. *
  1113. * @return void
  1114. * @triggers Controller.startup $this->Controller
  1115. */
  1116. public function testValidatePostRadio()
  1117. {
  1118. $event = new Event('Controller.startup', $this->Controller);
  1119. $this->Controller->Security->startup($event);
  1120. $fields = 'c2226a8879c3f4b513691295fc2519a29c44c8bb%3An%3A0%3A%7B%7D';
  1121. $unlocked = '';
  1122. $debug = urlencode(json_encode([
  1123. '/articles/index',
  1124. [],
  1125. []
  1126. ]));
  1127. $this->Controller->request->data = [
  1128. '_Token' => compact('fields', 'unlocked', 'debug'),
  1129. ];
  1130. $result = $this->validatePost('SecurityException', 'Bad Request');
  1131. $this->assertFalse($result);
  1132. $this->Controller->request->data = [
  1133. '_Token' => compact('fields', 'unlocked', 'debug'),
  1134. 'Test' => ['test' => '']
  1135. ];
  1136. $result = $this->validatePost();
  1137. $this->assertTrue($result);
  1138. $this->Controller->request->data = [
  1139. '_Token' => compact('fields', 'unlocked', 'debug'),
  1140. 'Test' => ['test' => '1']
  1141. ];
  1142. $result = $this->validatePost();
  1143. $this->assertTrue($result);
  1144. $this->Controller->request->data = [
  1145. '_Token' => compact('fields', 'unlocked', 'debug'),
  1146. 'Test' => ['test' => '2']
  1147. ];
  1148. $result = $this->validatePost();
  1149. $this->assertTrue($result);
  1150. }
  1151. /**
  1152. * test validatePost uses here() as a hash input.
  1153. *
  1154. * @return void
  1155. * @triggers Controller.startup $this->Controller
  1156. */
  1157. public function testValidatePostUrlAsHashInput()
  1158. {
  1159. $event = new Event('Controller.startup', $this->Controller);
  1160. $this->Security->startup($event);
  1161. $fields = 'b0914d06dfb04abf1fada53e16810e87d157950b%3A';
  1162. $unlocked = '';
  1163. $debug = urlencode(json_encode([
  1164. 'another-url',
  1165. ['Model.username', 'Model.password'],
  1166. []
  1167. ]));
  1168. $this->Controller->request->data = [
  1169. 'Model' => ['username' => '', 'password' => ''],
  1170. '_Token' => compact('fields', 'unlocked', 'debug')
  1171. ];
  1172. $this->assertTrue($this->validatePost());
  1173. $request = $this->getMockBuilder('Cake\Network\Request')
  1174. ->setMethods(['here'])
  1175. ->getMock();
  1176. $request->expects($this->at(0))
  1177. ->method('here')
  1178. ->will($this->returnValue('/posts/index?page=1'));
  1179. $request->expects($this->at(1))
  1180. ->method('here')
  1181. ->will($this->returnValue('/posts/edit/1'));
  1182. $request->data = $this->Controller->request->data;
  1183. $this->Controller->request = $request;
  1184. $this->assertFalse($this->validatePost('SecurityException', 'URL mismatch in POST data (expected \'another-url\' but found \'/posts/index?page=1\')'));
  1185. $this->assertFalse($this->validatePost('SecurityException', 'URL mismatch in POST data (expected \'another-url\' but found \'/posts/edit/1\')'));
  1186. }
  1187. /**
  1188. * test that blackhole doesn't delete the _Token session key so repeat data submissions
  1189. * stay blackholed.
  1190. *
  1191. * @return void
  1192. * @triggers Controller.startup $this->Controller
  1193. */
  1194. public function testBlackHoleNotDeletingSessionInformation()
  1195. {
  1196. $event = new Event('Controller.startup', $this->Controller);
  1197. $this->Controller->Security->startup($event);
  1198. $this->Controller->Security->blackHole($this->Controller, 'auth');
  1199. $this->assertTrue($this->Controller->Security->session->check('_Token'), '_Token was deleted by blackHole %s');
  1200. }
  1201. /**
  1202. * Test generateToken()
  1203. *
  1204. * @return void
  1205. */
  1206. public function testGenerateToken()
  1207. {
  1208. $request = $this->Controller->request;
  1209. $this->Security->generateToken($request);
  1210. $this->assertNotEmpty($request->params['_Token']);
  1211. $this->assertTrue(isset($request->params['_Token']['unlockedFields']));
  1212. }
  1213. /**
  1214. * Test unlocked actions
  1215. *
  1216. * @return void
  1217. * @triggers Controller.startup $this->Controller
  1218. */
  1219. public function testUnlockedActions()
  1220. {
  1221. $_SERVER['REQUEST_METHOD'] = 'POST';
  1222. $event = new Event('Controller.startup', $this->Controller);
  1223. $this->Controller->request->data = ['data'];
  1224. $this->Controller->Security->unlockedActions = 'index';
  1225. $this->Controller->Security->blackHoleCallback = null;
  1226. $result = $this->Controller->Security->startup($event);
  1227. $this->assertNull($result);
  1228. }
  1229. /**
  1230. * Test that debug token format is right
  1231. *
  1232. * @return void
  1233. * @triggers Controller.startup $this->Controller
  1234. */
  1235. public function testValidatePostDebugFormat()
  1236. {
  1237. $event = new Event('Controller.startup', $this->Controller);
  1238. $this->Controller->Security->startup($event);
  1239. $unlocked = 'Model.username';
  1240. $fields = ['Model.hidden', 'Model.password'];
  1241. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1242. $debug = urlencode(json_encode([
  1243. '/articles/index',
  1244. ['Model.hidden', 'Model.password'],
  1245. ['Model.username'],
  1246. ['not expected']
  1247. ]));
  1248. $this->Controller->request->data = [
  1249. 'Model' => [
  1250. 'username' => 'mark',
  1251. 'password' => 'sekret',
  1252. 'hidden' => '0'
  1253. ],
  1254. '_Token' => compact('fields', 'unlocked', 'debug')
  1255. ];
  1256. $result = $this->validatePost('SecurityException', 'Invalid security debug token.');
  1257. $this->assertFalse($result);
  1258. $debug = urlencode(json_encode('not an array'));
  1259. $result = $this->validatePost('SecurityException', 'Invalid security debug token.');
  1260. $this->assertFalse($result);
  1261. }
  1262. /**
  1263. * test blackhole will now throw passed exception if debug enabled
  1264. *
  1265. * @expectedException Cake\Controller\Exception\SecurityException
  1266. * @expectedExceptionMessage error description
  1267. * @return void
  1268. */
  1269. public function testBlackholeThrowsException()
  1270. {
  1271. $this->Security->config('blackHoleCallback', '');
  1272. $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
  1273. }
  1274. /**
  1275. * test blackhole will throw BadRequest if debug disabled
  1276. *
  1277. * @return void
  1278. */
  1279. public function testBlackholeThrowsBadRequest()
  1280. {
  1281. $this->Security->config('blackHoleCallback', '');
  1282. $message = '';
  1283. Configure::write('debug', false);
  1284. try {
  1285. $this->Security->blackHole($this->Controller, 'auth', new SecurityException('error description'));
  1286. } catch (SecurityException $ex) {
  1287. $message = $ex->getMessage();
  1288. $reason = $ex->getReason();
  1289. }
  1290. $this->assertEquals('The request has been black-holed', $message);
  1291. $this->assertEquals('error description', $reason);
  1292. }
  1293. /**
  1294. * Test that validatePost fails with tampered fields and explanation
  1295. *
  1296. * @return void
  1297. * @triggers Controller.startup $this->Controller
  1298. */
  1299. public function testValidatePostFailTampering()
  1300. {
  1301. $event = new Event('Controller.startup', $this->Controller);
  1302. $this->Controller->Security->startup($event);
  1303. $unlocked = '';
  1304. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1305. $debug = urlencode(json_encode([
  1306. '/articles/index',
  1307. $fields,
  1308. []
  1309. ]));
  1310. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1311. $fields .= urlencode(':Model.hidden|Model.id');
  1312. $this->Controller->request->data = [
  1313. 'Model' => [
  1314. 'hidden' => 'tampered',
  1315. 'id' => '1',
  1316. ],
  1317. '_Token' => compact('fields', 'unlocked', 'debug')
  1318. ];
  1319. $result = $this->validatePost('SecurityException', 'Tampered field \'Model.hidden\' in POST data (expected value \'value\' but found \'tampered\')');
  1320. $this->assertFalse($result);
  1321. }
  1322. /**
  1323. * Test that validatePost fails with tampered fields and explanation
  1324. *
  1325. * @return void
  1326. * @triggers Controller.startup $this->Controller
  1327. */
  1328. public function testValidatePostFailTamperingMutatedIntoArray()
  1329. {
  1330. $event = new Event('Controller.startup', $this->Controller);
  1331. $this->Controller->Security->startup($event);
  1332. $unlocked = '';
  1333. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1334. $debug = urlencode(json_encode([
  1335. '/articles/index',
  1336. $fields,
  1337. []
  1338. ]));
  1339. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1340. $fields .= urlencode(':Model.hidden|Model.id');
  1341. $this->Controller->request->data = [
  1342. 'Model' => [
  1343. 'hidden' => ['some-key' => 'some-value'],
  1344. 'id' => '1',
  1345. ],
  1346. '_Token' => compact('fields', 'unlocked', 'debug')
  1347. ];
  1348. $result = $this->validatePost('SecurityException', 'Unexpected field \'Model.hidden.some-key\' in POST data, Missing field \'Model.hidden\' in POST data');
  1349. $this->assertFalse($result);
  1350. }
  1351. /**
  1352. * Test that debug token should not be sent if debug is disabled
  1353. *
  1354. * @return void
  1355. * @triggers Controller.startup $this->Controller
  1356. */
  1357. public function testValidatePostUnexpectedDebugToken()
  1358. {
  1359. $event = new Event('Controller.startup', $this->Controller);
  1360. $this->Controller->Security->startup($event);
  1361. $unlocked = '';
  1362. $fields = ['Model.hidden' => 'value', 'Model.id' => '1'];
  1363. $debug = urlencode(json_encode([
  1364. '/articles/index',
  1365. $fields,
  1366. []
  1367. ]));
  1368. $fields = urlencode(Security::hash(serialize($fields) . $unlocked . Security::salt()));
  1369. $fields .= urlencode(':Model.hidden|Model.id');
  1370. $this->Controller->request->data = [
  1371. 'Model' => [
  1372. 'hidden' => ['some-key' => 'some-value'],
  1373. 'id' => '1',
  1374. ],
  1375. '_Token' => compact('fields', 'unlocked', 'debug')
  1376. ];
  1377. Configure::write('debug', false);
  1378. $result = $this->validatePost('SecurityException', 'Unexpected \'_Token.debug\' found in request data');
  1379. $this->assertFalse($result);
  1380. }
  1381. /**
  1382. * Auth required throws exception token not found
  1383. *
  1384. * @return void
  1385. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1386. * @expectedExceptionMessage '_Token' was not found in request data.
  1387. * @triggers Controller.startup $this->Controller
  1388. */
  1389. public function testAuthRequiredThrowsExceptionTokenNotFoundPost()
  1390. {
  1391. $this->Controller->Security->config('requireAuth', ['protected']);
  1392. $this->Controller->request->params['action'] = 'protected';
  1393. $this->Controller->request->data = 'notEmpty';
  1394. $this->Controller->Security->authRequired($this->Controller);
  1395. }
  1396. /**
  1397. * Auth required throws exception token not found in Session
  1398. *
  1399. * @return void
  1400. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1401. * @expectedExceptionMessage '_Token' was not found in session.
  1402. * @triggers Controller.startup $this->Controller
  1403. */
  1404. public function testAuthRequiredThrowsExceptionTokenNotFoundSession()
  1405. {
  1406. $this->Controller->Security->config('requireAuth', ['protected']);
  1407. $this->Controller->request->params['action'] = 'protected';
  1408. $this->Controller->request->data = ['_Token' => 'not empty'];
  1409. $this->Controller->Security->authRequired($this->Controller);
  1410. }
  1411. /**
  1412. * Auth required throws exception controller not allowed
  1413. *
  1414. * @return void
  1415. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1416. * @expectedExceptionMessage Controller 'NotAllowed' was not found in allowed controllers: 'Allowed, AnotherAllowed'.
  1417. * @triggers Controller.startup $this->Controller
  1418. */
  1419. public function testAuthRequiredThrowsExceptionControllerNotAllowed()
  1420. {
  1421. $this->Controller->Security->config('requireAuth', ['protected']);
  1422. $this->Controller->request->params['controller'] = 'NotAllowed';
  1423. $this->Controller->request->params['action'] = 'protected';
  1424. $this->Controller->request->data = ['_Token' => 'not empty'];
  1425. $this->Controller->request->session()->write('_Token', [
  1426. 'allowedControllers' => ['Allowed', 'AnotherAllowed']
  1427. ]);
  1428. $this->Controller->Security->authRequired($this->Controller);
  1429. }
  1430. /**
  1431. * Auth required throws exception controller not allowed
  1432. *
  1433. * @return void
  1434. * @expectedException Cake\Controller\Exception\AuthSecurityException
  1435. * @expectedExceptionMessage Action 'NotAllowed::protected' was not found in allowed actions: 'index, view'.
  1436. * @triggers Controller.startup $this->Controller
  1437. */
  1438. public function testAuthRequiredThrowsExceptionActionNotAllowed()
  1439. {
  1440. $this->Controller->Security->config('requireAuth', ['protected']);
  1441. $this->Controller->request->params['controller'] = 'NotAllowed';
  1442. $this->Controller->request->params['action'] = 'protected';
  1443. $this->Controller->request->data = ['_Token' => 'not empty'];
  1444. $this->Controller->request->session()->write('_Token', [
  1445. 'allowedActions' => ['index', 'view']
  1446. ]);
  1447. $this->Controller->Security->authRequired($this->Controller);
  1448. }
  1449. /**
  1450. * Auth required throws exception controller not allowed
  1451. *
  1452. * @return void
  1453. * @triggers Controller.startup $this->Controller
  1454. */
  1455. public function testAuthRequired()
  1456. {
  1457. $this->Controller->Security->config('requireAuth', ['protected']);
  1458. $this->Controller->request->params['controller'] = 'Allowed';
  1459. $this->Controller->request->params['action'] = 'protected';
  1460. $this->Controller->request->data = ['_Token' => 'not empty'];
  1461. $this->Controller->request->session()->write('_Token', [
  1462. 'allowedActions' => ['protected'],
  1463. 'allowedControllers' => ['Allowed'],
  1464. ]);
  1465. $this->assertTrue($this->Controller->Security->authRequired($this->Controller));
  1466. }
  1467. }