SecurityComponentTest.php 56 KB

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